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)
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> if (count($images) == 0) { <li>No uploaded images found</li> } else foreach ($images as $id => $filename) { <li> <a href="view.php?id= echo $id "> echo htmlSpecialChars($filename) </a> </li> } </ul> </body> </html>
No comments:
Post a Comment