When we are querying a database with PHP It will be very useful for us to know the number of results we obtain. There are several ways to do this. The first is through the programmatic API of PHP and the other which is through a query SQL.
In this case we are going to retrieve the number of results of a query to a database programmatically in PHP.
So, the first thing we will do is connect to the database.
@ $db = new mysqli(localhost, "root", "password", "library");
if ($db->connect_error)
die('Connection Error ('.$db->connect_errno.')'.$db->connect_error);
We see that we have connected to a database called “library” with the user “root” and the password “password”. Don’t stop reading the article how to connect to MySQL with PHP to see the connection process in more detail.
The next thing will be to make a query SQL about the database.
$query = "SELECT * FROM books";
$result = $db->query($query);
We set up a query SQL and we execute it on the database using query method. We can see that the query is simple and simply retrieves all the information from the books table.
Now we are going to see the number of results that the query has returned. For this we use the num_rows method on the result of the query.
$numrows = $result->num_rows;
echo "The number of elements is ".$numrows."
";
We will only have to close the connection to the database.
$result->free();
$db->close();
