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 get the first row of a result in MySQL using PHP?
- How to output XML from MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to use a MySQL union in PHP?
- How to generate a UUID in MySQL using PHP?
- How to get the version of MySQL using PHP?
- How to write an update query in MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to convert a MySQL timestamp to a datetime in PHP?
- How to join tables with PHP and MySQL?
See more codes...