0

I am working on the following script. Why am I always getting 0 using the COUNT(*) in my query against MySQL using prepared statement?

$num_query = "SELECT COUNT(*) FROM $tbl WHERE `tdisplay` = 1";
$stmt2 = $conn-> prepare($num_query);
$stmt2 -> execute();
$stmt2 -> store_result();
$rows = $stmt2->num_rows;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Mona Coder
  • 6,212
  • 18
  • 66
  • 128
  • 2
    Assuming the query succeeded you should always get 1 row, the one 1 containing the `COUNT`. – Nick Dec 16 '19 at 20:34
  • Thanks for reply but I am getting `0` and why `1` ? shouldn't It return all rows numbers? Same query in `PHPMyAdmin` is returning 414 – Mona Coder Dec 16 '19 at 20:37
  • You are checking the number of rows returned from the query. The query only returns one row, which has the count in it. Try replacing `$stmt2->store_result` with `$stmt2->bind_result($rows); $stmt2->fetch(); echo $rows;` – Nick Dec 16 '19 at 20:39
  • I can't reproduce. I always get 1. – Dharman Dec 16 '19 at 20:39
  • Are you sure you have mysqli exceptions switched on? How are you checking the value of `$rows`? – Dharman Dec 16 '19 at 20:41
  • @Nick, now I am getting `false` in return – Mona Coder Dec 16 '19 at 20:59
  • It sounds like your query is failing somewhere. You need to add error checking... – Nick Dec 16 '19 at 21:03
  • Does this answer your question? [mysqli\_fetch\_assoc() expects parameter / Call to a member function bind\_param() errors. How to get the actual mysql error and fix it?](https://stackoverflow.com/questions/22662488/mysqli-fetch-assoc-expects-parameter-call-to-a-member-function-bind-param) – Dharman Dec 17 '19 at 19:53
  • Also: [How to get count of rows in MySQL table using PHP?](https://stackoverflow.com/q/58227521/1839439) – Dharman Dec 17 '19 at 19:54

0 Answers0