Reputation: 171
I have this code to display my images in rows of 5 but for some reason the code adds an image at the end of the first row.
Is there an error with this code? If not, how do I change it to stop adding the extra image at the end of the first row.
Code:
$query = mysql_query("SELECT * FROM gallery WHERE gallery_number='$gallery_number'");
echo '<table width="960">';
$i = 0; //first, i set a counter
while($fetch = mysql_fetch_assoc($query)){
//counter is zero then we are start new row
if ($i==0){
echo '<tr>';
}
//here we creating normal cells <td></td>
$image_name = $fetch['image_name'];
$image_location = $fetch['image_location'];
echo '<td>'.'<img src="'.$image_location.'" alt="'.$image_name.'"/>'.'</td>';
//there is a magic - if our counter is greater then 5 we set counter to zero and close tr tag
if ($i>5){
$i=0;
echo '</tr>';
};
$i++; //$i = $i + 1 - counter + 1
}
echo '</table>';
Upvotes: 0
Views: 79
Reputation: 3172
You don't close TR. You are closing TR only if $i reaches 5, and you also don't open a new one. Check the result in the browser (Ctrl-U).
Your program should contain something like:
if ($i > 5) {
echo("</tr><tr>");
$i = 0;
}
It closes a full row and opens a new one. Also, you should open TR before the loop, and close after the loop. (Advanced task: eliminate empty TR pairs.)
Upvotes: 1
Reputation: 396
You are beginning the $i
count with 0
, so with your check, it will return 6 results.
if ($i>5){
$i=0;
echo '</tr>';
};
That should either be this:
if ($i>4){
$i=0;
echo '</tr>';
};
Or you could change your $i
counter to start at 1
and reset to 1
.
Upvotes: 1
Reputation: 10051
This code won't work for a couple of reasons.
First, think about how many times you are ACTUALLY creating <td>
s. You start your counter, $i
at 0
. You then only reset it after you reach 6
. You are looping too many times.
Second, with where you increment your counter, you will ONLY ever have 1 <tr>
creation. This is because you reset your counter to 0
. You then immediately increase it to 1. This will prevent the next <tr>
s from being created.
Upvotes: 0