I just want to count the number of rows in a table that already created in a database using php. I used mysqli(). I need the number of rows in the table as the output.
6 Answers
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {
/* fetch the first row as result */
$row = $result->fetch_assoc();
printf("Result set has %d rows.\n", $row['cc']);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
In fact it's a common question you can find the answer anywhere.
Like, http://php.net/manual/en/mysqli-result.num-rows.php
You could separate this problem in to two
- I wanna know how to connect to mysql.
- I wanna know how to write that sql instruction.
1 Comment
georg
Well, you and @RajibGhosh copypasted the same code, but unfortunately it's wrong. The result will always be 1.
<?php
$mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $mysqli->query("SELECT columnName from tablename")) {
/* determine number of rows result set */
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
/* close result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
EDIT:
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
2 Comments
georg
That's better, but still no cigar. There's no need to fetch all rows just to count them.
count(*) is a better option.Rajib Ghosh
@georg please check my updated comment.now is it ok :)
also you simply do this
"SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "
1 Comment
DontVoteMeDown
Please add some explanation about your answer.