php-mysqlHow to count the number of resulting rows in a MySQL database using PHP?
The number of resulting rows in a MySQL database can be counted using PHP by executing a SELECT COUNT(*) query. The following example code will return the number of rows in the users table:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT COUNT(*) FROM users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Number of rows: " . $row["COUNT(*)"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Output example
Number of rows: 5
The code consists of the following parts:
- Establishing a connection to the MySQL database using
$conn = new mysqli($servername, $username, $password, $dbname); - Executing the
SELECT COUNT(*)query using$result = $conn->query($sql); - Looping through the result set using
while($row = $result->fetch_assoc()) - Outputting the number of rows using
echo "Number of rows: " . $row["COUNT(*)"]; - Closing the connection using
$conn->close();
Helpful links
More of Php Mysql
- How to output XML from MySQL using PHP?
- How to get the version of MySQL using PHP?
- How to use a MySQL union in PHP?
- How to set a timeout for MySQL query in PHP?
- How to export data from MySQL to Excel using PHP?
- How to check if a record exists in PHP and MySQL?
- How to create an SSL connection to MySQL using PHP?
- How to get a single value from query in PHP MySQL?
- How to store a boolean value in a MySQL database using PHP?
- How to write an update query in MySQL using PHP?
See more codes...