I'm trying to count the number of rows in a table and thought that this was the correct way to do that:
$result = $db->query("SELECT COUNT(*) FROM `table`;");
$count = $result->num_rows;
But counts always returns (int)1
. If I use the same query in phpMyAdmin I get the right result. It sits in a table so I tried testing $count[0]
as well, but that returns NULL
.
What is the right way to do this?
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Always try to do an associative fetch, that way you can easy get what you want in multiple case result
Here's an example
$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";
I find this way more readable:
$result = $mysqli->query('select count(*) as `c` from `table`');
$count = $result->fetch_object()->c;
echo "there are {$count} rows in the table";
Not that I have anything against arrays...
This worked well for me.
// Veh Pro Count
$query_tvp = "SELECT count(*) as total from submit";
if ($result_tvp = $mysqli->query("$query_tvp")) {
/* determine number of rows result set */
$total_tvp = $result_tvp->fetch_row();
$total_tvp = $total_tvp['0'];
/* close result set */
$result_tvp->close();
}
echo "Total: $total_tvp";
its very sample.
$query="select count(*)as count from users";
$result=$connection->query($query);
$count=mysqli_fetch_assoc($result)["count"];
echo $count;
$result->num_rows; only returns the number of row(s) affected by a query. When you are performing a count(*) on a table it only returns one row so you can not have an other result than 1.
For me this works, this is when you want to count a repeated elements inside a register.
For example: number of people who mark 'yes' in a form.
table: users
register: vote
element of register: yes / no
$sql_user = "SELECT COUNT(*) FROM users WHERE vote = 'yes'";
$result1 = $mysqli->query($sql_user);
$row1 = $result1->fetch_row();
$n_yes = $row1['0'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.