PHP MySQL: Outputing to table Using fetch_assoc

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

Continued from previous post.

In an earlier post, we have used printf to output a table records.

printf ("%d %s %s %s", $row["id"], $row["artiste"], $row["album"], $row["year"] );

If we stick to the same table format, we will have to embed the php code into the HTML table. This is what made it hard for beginners to learn PHP.

Once we have the connection to the DB set, we can use fetch_assoc to fetch the row and use echo to build up the  HTML table.

And finally we just have to use printf to output the data to the HTML table.

<table border="1">
    $mysqli = new mysqli("localhost", "root", "", "allartist");

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

    $query = "select id, artiste, album, year from artist";

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

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            echo "<tr><td>" . $row["id"] . "</td><td>" . $row["artiste"] . "</td><td>" . $row["album"] . "</td><td>" . $row["year"] . "</td></tr>";
            //    printf ("%d %s %s %s", $row['id'], $row["artiste"], $row["album"], $row["year"] );

        /* free result set */

    /* close connection */

If you look at the code above, and compare it with the earlier post, you could see that the main line that I have added is:

echo "<tr><td>" . $row["id"] . "</td><td>" . $row["artiste"] . "</td><td>" . $row["album"] . "</td><td>" . $row["year"] . "</td></tr>";

Running the above code will display the table below.


Series Navigation<< PHP MySQL: Outputing data to HTML table I