Answer the question
In order to leave comments, you need to log in
Why does a SELECT COUNT(*) query throw an error and not return '0' if there is no record matching 'WHERE'?
Let's say given a category with '$cat_id = 5' .
I need to know the number of entries where category_id = 5 . (I’ll say in advance - there are no records with category_id = 5 in the table )
In phpmyadmin I write a query:
SELECT COUNT(*) FROM table_name WHERE category_id = 5
Returns the COUNT column with value '0' . That's right! $database->query('SELECT COUNT(*) AS count FROM table_name WHERE category_id = :category_id');
$database->bind(':category_id', $cat_id);
$result = $database->single();
$favs_count = $result['count'];
Gives an error message:...MySQL server version for the right syntax to use near '-15, 15' at line 1...
Answer the question
In order to leave comments, you need to log in
Well, look carefully at the error, as far as I understand, it says that there is a syntax error in the request, try doing this
$database->query('SELECT COUNT(*) AS count FROM table_name WHERE category_id = :category_id');
$database->bind(':category_id', abs(intval($cat_id)));
$result = $database->single();
$favs_count = $result['count'];
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question