PHP newbie here again looking for some more help. I am trying to create a html table using information queried from a database. I would like three columns and the number of rows would be dynamic based on information gathered during the query. Briefly, it would look like:
picture1 | picture2 | picture3
==================
lablel1 | label2 | label3
==================
picture4 | etc. etc.

What I am getting right now is:
picture1 | picture1 | picture1
==================
picture2 | picture2 | picture2

The loop is working, if only incorrectly; and I can't figure out how to apply the corresponding labels on the next row. Here's my code:

if (($result)||(mysql_errno == 0)) 
{ 
  echo "<table width='100%' border='0' cellspacing='0' cellpadding='0'>"; 
  if (mysql_num_rows($result)>0) 
  {  
    //display the data 
    while ($rows = mysql_fetch_array($result,MYSQL_ASSOC)) 
    { 
	   echo "<tr>";
       //loop thru the serials to create three columns
	   $i = 0;
	   while ($i < '3')
	   {
      	echo "<td><img src='/images/{$rows['FileDirectory']}/{$rows['Graphic']}.jpg' width='150' height='112' /></td>"; 
	  	$i++;
	   }
	   echo "</tr>";
    } 
  }else{ 
    echo "<tr><td colspan='" . ($i+1) . "'>No Results found!</td></tr>"; 
  } 
  echo "</table>"; 
}else{ 
  echo "Error in running query :". mysql_error(); 
}

Any help is appreciated. Thanks.

Dani AI

Generated

Quick diagnosis and goal recap (for ): the loop in the original code fetches one DB row and then prints that same row three times. 's tip about using an integer (not the string '3') is correct but only hides a minor bug — it does not change the overall approach. The reliable pattern is: read rows sequentially, buffer groups of three, then print an image row followed by a label row for that group. Fill any incomplete final group with empty cells so the table layout stays consistent.

Algorithm (high level)

  1. Run the query and stream rows.
  2. Push each row into a small buffer.
  3. When the buffer reaches three items (or after the loop ends), output one <tr> of image cells and one <tr> of label cells for that buffer, then clear it.
  4. If the last buffer has fewer than three rows, output blank <td> cells to pad to three.

Practical example (uses mysqli + prepared statements; safer and future-proof)

<?php
$series = $_GET['series'] ?? '';
$mysqli = new mysqli('host','user','pass','db');
$stmt = $mysqli->prepare('SELECT Label, FileDirectory, Graphic FROM tblTitles WHERE FileDirectory = ?');
$stmt->bind_param('s',$series);
$stmt->execute();
$res = $stmt->get_result();
$buf = [];
echo \"<table>\n\";
while ($r = $res->fetch_assoc()) {
$buf[] = $r;
if (count($buf) === 3) {
// print images row
echo \"<tr>\";
foreach ($buf as $b) echo \"<td><img src=\\"/images/\".htmlspecialchars($b['FileDirectory']).\"/\".htmlspecialchars($b['Graphic']).\".jpg\\" alt=\\"\".htmlspecialchars($b['Label']).\"\\"></td>\";
echo \"</tr>\n<tr>\";
// print labels row
foreach ($buf as $b) echo \"<td>\".htmlspecialchars($b['Label']).\"</td>\";
echo \"</tr>\n\";
$buf = [];
}
}
// handle remainder (pad to 3)
if ($buf) {
echo \"<tr>\";
foreach ($buf as $b) echo \"<td><img src=\\"/images/\".htmlspecialchars($b['FileDirectory']).\"/\".htmlspecialchars($b['Graphic']).\".jpg\\" alt=\\"\".htmlspecialchars($b['Label']).\"\\"></td>\";
for ($i = count($buf); $i < 3; $i++) echo \"<td></td>\";
echo \"</tr>\n<tr>\";
foreach ($buf as $b) echo \"<td>\".htmlspecialchars($b['Label']).\"</td>\";
for ($i = count($buf); $i < 3; $i++) echo \"<td></td>\";
echo \"</tr>\n\";
}
echo \"</table>\n\";
?>

Notes and cautions: use prepared statements (shown above) to avoid SQL injection, escape labels with htmlspecialchars, include useful alt text, and optionally check for missing image files and show a placeholder. Also, the old ext/mysql functions are deprecated and were removed in PHP 7 — prefer MySQLi or PDO for new code; see the PHP manual for details. (php.net)

Finally, and raised good points about format and edge cases — the buffering approach above addresses both dynamic row count and leftover cells.

Recommended Answers

All 6 Replies

Hi.

How can you expect to see "label" if in your code there is no $row for example.
I mean you print only $rows and $rows extracted form DB as I can see.

Show us your query, pls.

Hi.

How can you expect to see "label" if in your code there is no $row for example.
I mean you print only $rows and $rows extracted form DB as I can see.

Show us your query, pls.

I wasn't expecting to see a row with the "labels" on them. I couldn't figure out how to make that happen. When everything I tried to get the pictures to appear properly failed, I stopped work on it. Thats why the labels are not in the code. Here is the query:

$series = $_GET['series'];

$query = "SELECT * FROM tblTitles WHERE FileDirectory = '$series'"; //Make the query
$result = @mysql_query ($query); // Run the query

There are only four rows in tblTitles: Label, Series, FileDirectory, and Graphic.

Thanks for looking at the problem.

And what format do you exactly want ?

picture1 | picture2 | picture3
==================
lablel1 | label2 | label3
==================


Three pictures in row next the three labels and next pictures 4-6 and labels 4-6 ?

And what format do you exactly want ?

picture1 | picture2 | picture3
==================
lablel1 | label2 | label3
==================


Three pictures in row next the three labels and next pictures 4-6 and labels 4-6 ?

Etc., etc. Yes. Since its dynamic, I have no idea how many rows there would be. Another thing I just thought of is left-over cells, i.e. if the number of pictures/labels is not divisible by 3 there will be a couple of left-over pictures that would need blank cells to complete the row.

This is something I could never quite get my head around, I resorted to adding 3 images in my database and printing them out that way. Would also be interested if anyone has an answer

change:

$i = 0;	   
while ($i < '3')

to:

$i = 0;	   
while ($i < 3)

That may help a little

regards Niek

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.