PHP MySQL: Select Count Using fetch_assoc()

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:

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

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

$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 */
    $result->free();
}

/* close connection */
$mysqli->close();
?>

Here the screenshot after running the script above:

select2

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