PHP MySQL: Select Count Using fetch_assoc()

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

If we are to use

select count(*) from artist

in the query statement, we can use the fetch_assoc() method provided by PHP.

The syntax is:

array mysqli_result::fetch_assoc ( void )

select count(*) from artist

will only return a row and a column.  For associative array, we would need to have a column name.

We can assign a column name cnt as

select count(*) as cnt from artist

The PHP code would be as below:

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

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

$query = "select count(*) as cnt from artist ";

if ($result = $mysqli->query($query)) {

    /* fetch associative array */

    $row = $result->fetch_assoc();
    printf("Number of records:  %s", $row["cnt"]);

    /* free result set */

/* close connection */

Here the screenshot after running the script above:


Series Navigation<< PHP MySQL: Select count
PHP MySQL: Select to display table using fetch_assoc >>

Leave a comment

Leave a Reply