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">
    <tr>
        <th>ID</th>
        <th>artiste</th>
        <th>album</th>
        <th>year</th>
    </tr>
    <?php
    $mysqli = new mysqli("localhost", "root", "", "allartist");

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

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

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

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.

html_table_output

PHP: Our first PHP script

This entry is part 2 of 54 in the series PHP Tutorial

We will first look at a few PHP examples.  Here I assume that you have some understanding of HTML which is sufficed for us for now.

<html>
 <head>
  <title>PHP Test</title>
 </head>
 <body>
 <?php echo '<p>Hello World</p>'; ?> 
 </body>
</html>
Try The Code

Echo is similar to writeln in C.

In this example, the entire string <p>Hello World</p> will be output to the browser and this string is also what the browser will see.

And as for us, we will see Hello World in the browser when the script is ran.