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 use a variable in a MySQL query using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to use a MySQL union in PHP?
- How to change database in MySQL with PHP?
- How to check if a record exists in PHP and MySQL?
- How to generate a UUID in MySQL using PHP?
- How to set a timeout for MySQL query in PHP?
- How to join tables with PHP and MySQL?
- How to create an SSL connection to MySQL using PHP?
- How to fetch data from MySQL in PHP?
See more codes...