PHP MySQL: Select a single record using fetch_assoc

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

A single record in the table can be retrieved by using fetch_assoc().

We have this table as below and let’s say we ask ourselves when was Nirvana’s Smell Like Teen Spirit released.

1Rod StewartMaggie May1973
2New OrderSubstance1987
3NirvanaSmell Like Teen Spirit1992
4Rod StewartOut of Order1988
Run the SQL

We first have to make some adjustments to the query statement:

select year from artist where artiste='Nirvana' and album='Smell Like Teen Spirit'
Run the SQL
$mysqli = new mysqli("localhost", "root", "", "allartist");

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

$query = "select year as yr from artist where artiste='Nirvana' and album='Smell Like Teen Spirit'";

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

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {
        printf ("Smell Like Teen Spirit was released in: %d", $row["yr"]);
        echo "<br>";

    /* free result set */

/* close connection */

We have used associative array method fetch_assoc().

If the above script is ran, the output in the browser is as below:


Series Navigation<< PHP MySQL: Display records using fetch_array
PHP MySQL: using data_seek to fetch row >>