OldWest
OldWest

Reputation: 2385

Apply MySQL COUNT() in php Query w/ Selected Column Names

I am trying to apply COUNT() in a query and I have it working like so:

$sql = "SELECT id, Title, images, recdate, 'item' AS type FROM ads_list WHERE to_days(now())<=(to_days(recdate)+14)";

I've tried:

1. $sql = "SELECT id, Title, images, recdate, 'item' AS type COUNT(*) FROM ads_list WHERE to_days(now())<=(to_days(recdate)+14)";

2. $sql = "SELECT COUNT(*) id, Title, images, recdate, 'item' AS type FROM ads_list WHERE to_days(now())<=(to_days(recdate)+14)";

3. $sql = "SELECT COUNT(id), Title, images, recdate, 'item' AS type FROM ads_list WHERE to_days(now())<=(to_days(recdate)+14)";

4. $sql = "SELECT id, Title, images, recdate, 'item' AS type FROM ads_list WHERE to_days(now())<=(to_days(recdate)+14) COUNT(*)";

What am I doing wrong?

Upvotes: 0

Views: 554

Answers (1)

Tim
Tim

Reputation: 1011

Count(*) is a group by function, it returns the count of rows selected. You must have a group by function on any columns which are not included in the group by clause. So, you can do:

SELECT count(*) as 'Count' FROM ads_list WHERE ...

but you can't (directly) select one group by function and four standard columns. What are you trying to achieve with the count(*)?

For total rows, you can use mysql_num_rows($result_resource). If you need the rows and the count (and you are using standard mysql library) that is probably the best way to get what you want. If you don't need the rows (only the count) then use count(*).

Upvotes: 1

Related Questions