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 change database in MySQL with PHP?
- How to get the version of MySQL using PHP?
- How to create an SSL connection to MySQL using PHP?
- How to update to null value in MySQL using PHP?
- How to use utf8mb4_unicode_ci in MySQL with PHP?
- How to check the result of an insert in PHP and MySQL?
- How to use MySQL transactions in PHP?
- How to get a single value from query in PHP MySQL?
- How to get table column names in PHP MySQL?
See more codes...