R
R
REVES2014-07-16 23:52:49
PHP
REVES, 2014-07-16 23:52:49

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!
In PHP I write a request:
$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...

NOTE: If you substitute in $cat_id the value that is in the records in the table, then everything works: both in phpmyadmin and in php . But! I need that in the absence of records with '$cat_id = 5' in the array result['count'] was: FALSE or '0' ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lorem Ipsum, 2014-07-17
@nobodynoone

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 question

Ask a Question

731 491 924 answers to any question