MySQL Count not functioning

I'm having trouble using the COUNT function in MySQL.
Now, I searched for an answer, and the first thing I found was this, however it wanted to count each distinct value. I found this About.com page which helped me. Just making sure this isn't a duplicate, but keep reading.

I'm using MySQLi.

My code is simple, I'm trying to count the amount of times in the database, "users," that "admin" is listed as "true." Keep in mind that it's not true as in a boolean, but a string that can contain other values.

mysqli_query($con, "SELECT COUNT(*) FROM users WHERE admin='true'");

That didn't seem to work. I tried adding echo in front of the query, but I can't get the amount of times admin is true — it should echo 1.

Am I doing something wrong? I haven't found much on this subject online and I was reluctant to post it here but... I am :P
Thanks in advance!

Upvotes: 1

Views: 86

Answers (2)

PlausibleSarge
PlausibleSarge

Reputation: 2223

You don't need to fetch the results

$res = mysqli_query($con, "SELECT COUNT(*) FROM users WHERE admin='true'");
$number_of_rows = mysqli_num_rows($res);

according to this page

http://php.net/manual/en/mysqli-result.num-rows.php

this is untested right now

Upvotes: 0

jh314
jh314

Reputation: 27792

You need to fetch the results:

$result = mysqli_query($con, "SELECT COUNT(*) FROM users WHERE admin='true'");

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
printf ("%s \n", $row["COUNT(*)"]);

More info on mysqli_fetch_array can be found here.

Upvotes: 1

Related Questions