HomeMySQL Page 3 - Displaying Multiple Records Per Row in a MySQL Query Result Set
Digging Deeper - MySQL
Ever wonder how you can query a database and display the result set in something other than a one record per row layout? Keeping in mind that the simple answer is always the best one, I found a solution that keeps to that premise and solves an issue that seemed impossible not long ago. In a word, the answer, lies in the loop. An additional one, that is. But first, lets define and explain the general look and functionality of our project.
We start once again with the code needed to connect to the mysql server and request info from the query string attached to the URL. It is important to clean up query strings before you submit a request to the database. One of the simpliest and most effective means to do so is to use the built in PHP 'htmlspecialchars' function which prevents html markup from adding dangerous code to your query. The function has more capabilities then presented here, but in general it does the following.
· & (ampersand) becomes '&'
" " (double quote) becomes '"' when ENT_NOQUOTES is not set.
' ' (single quote) becomes ''' only when ENT_QUOTES is set.
< (less than) becomes '<'
> (greater than) becomes '>'
<?php require("../../includes/db_config.php"); // connect to mysql server from protected directory if(isset($_GET['CAT']) && ($_GET['AID'])) { $CAT = htmlspecialchars($_GET['CAT']); // clean up query string variable $AID = htmlspecialchars($_GET['AID']); // clean up query string variable $LOC = htmlspecialchars($_GET['LOC']); // clean up query string variable
// get album name first to populate title bar $sql_T = "SELECT albums.albumNAME FROM albums WHERE catID = '$CAT' AND albumID = '$AID' "; $sql_T_result = @mysql_query($sql_T, $connection) or die ("Could not execute your select albumNAME request"); $row_T = @mysql_fetch_array($sql_T_result); $NAME = stripslashes($row_T['albumNAME']);
// get images from album $sql = " SELECT albums.albumNAME, images.imgID, images.catID, images.albumID, images.locID, images.imgTITLE, images.thumbPATH, images.thumbNAME, images.copyright FROM images, albums WHERE images.catID = '$CAT' AND images.albumID = '$AID' AND images.albumID = albums.albumID ORDER BY copyright, thumbNAME";
$result = @mysql_query($sql, $connection); if(!$result) { print "Could not execute your select images request"; exit; }
$num = @mysql_num_rows($result); // you choose how many columns you want to display in each table row $thumbcols = 5; // quick and dirty formula to figure out how many rows you will need $thumbrows = 1+ round($num / $thumbcols); } ? >