PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Storing Images in MySQL Revisited

Outputting a List of Images

The final step is to list to output a list of all files that have been uploaded. We can do this by performing a select on the table, then looping over the returned files.

It is important to specify which fields you want to retrieve from the table, since if you select all (using *) it will result in the file data of every single image being returned. This may bog down your server significantly.

In the following code, we retrieve a list of image IDs and corresponding filenames (for display purposes) and build an array that we can easily loop over.

This code also checks if there are no images and displays a corresponding message accordingly.

Listing 10 Displaying a list of uploaded images (index.php)
<?php
    require_once('globals.php');
 
    $query = sprintf('select image_id, filename from images');
    $result = mysql_query($query, $db);
 
    $images = array();
 
    while ($row = mysql_fetch_array($result)) {
        $id = $row['image_id'];
        $images[$id] = $row['filename'];
    }
?>
<html>
    <head>
        <title>Uploaded Images</title>
    </head>
    <body>
        <div>
            <h1>Uploaded Images</h1>
 
            <p>
                <a href="upload.php">Upload an image</a>
            </p>
 
            <ul>
                <?php if (count($images) == 0) { ?>
                    <li>No uploaded images found</li>
                <?php } else foreach ($images as $id => $filename) { ?>
                    <li>
                        <a href="view.php?id=<?php echo $id ?>">
                            <?php echo htmlSpecialChars($filename)  ?>
                        </a>
                    </li>
                <?php } ?>
            </ul>
    </body>
</html>

In This Article



Bonus listings: 1 available