PHP MySQL: Select count

This entry is part 9 of 17 in the series PHP & MySQL

When it comes to querying a database, we always like to use select count to get the number of records in the table.

select count(*) from artist

However, let’s look at the code below.

To get the select count, we first pass the query string into $mysqli->query().

$mysqli = new mysqli("localhost", "root", "", "allartist");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s", mysqli_connect_error());

if ($result = $mysqli->query("SELECT * FROM artist")) {

    /* determine number of rows result set */
    $row_cnt = $result->num_rows;

    printf("Result set has %d rows.", $row_cnt);

    /* close result set */

/* close connection */

If connection to the DB is successful, we should get the following screenshot displayed on the browser.

select count

We are using

select * from artist

and yet we are able to get the number of records in the table.  This is because we are using OOP way of programming.

$result = $mysqli->query("SELECT * FROM artist")

In OOP, a variable is an object.  After executing the above statement, the relevant methods and properties associated with the object could be used.

In this case we have used

$row_cnt = $result->num_rows;

to retrieve the number of records in the table artist.

Series Navigation<< PHP MySQL: Update, non OOP style
PHP MySQL: Select Count Using fetch_assoc() >>