I have a gallery page I am working on and cannot seem to get the next set of images to load correctly by using GET parameter page=2.
I am using a table, with 6 images, and next and previous buttons.
When i click Next from page1 however, it loads images 8 to 13, instead of the agreed-upon 7 to 12.
The code is here:
<?php
echo "<table width=\"490\" border=\"1\" align=\"center\">";
if(isset($_GET['page'])){
//Read Page, Set Start image, End image
$cur_page=abs($_GET['page']);
//if the page is page1, then set the defaults
if($cur_page==1){
$prev_page=0;
$next_page=2;
$start_img=0;
$last_img=6;
}
//if the page is not page1, calculate the defaults
else{
$prev_page=$cur_page-1;
$next_page=$cur_page+1;
$start_img=(($cur_page-1)*6)+1;
$last_img=$start_img+5;
}
}else{
//Page=1 start image=1 end image=6
$cur_page=0;
$prev_page=1;
$next_page=2;
$start_img=0;
$last_img=6;
}
//Do the sql query for the images
$sql="SELECT * FROM images LIMIT $start_img, 6";
$result = mysql_query($sql, $conn) or die(mysql_error());
//Set a counter variable to iterate the image display
$count=0;
//Begin the table that displays the images.
while ($newArray = mysql_fetch_array($result)) {
$count++;
//Print the odd-numbered column first
if($count%2==1){
echo "<tr><td width=\"50%\"><a href=\"$newArray[Pic_Address]\">$newArray[Pic_Address]</a></td>";
//Print the even-numbered column next
}else{
echo "<td width=\"50%\"><a href=\"$newArray[Pic_Address]\">$newArray[Pic_Address]</a></td></tr>";
}
}
//print the next and previous Links
echo "<tr>";
if($prev_page==0){echo "<td align=\"center\">Prev</td>";}else{echo "<td align=\"center\"><a href=\"index.php?page=$prev_page\">Prev</a></td>";};
echo "<td align=\"center\"><a href=\"index.php?page=$next_page\">Next</a></td>";
echo "</tr>
</table>";
//Printscreen to test the page-load variables.
echo " <p align=\"center\">
current page=$cur_page <br>
prev_page=$prev_page <br>
next_page=$next_page <br>
start_img=$start_img <br>
last_img=$last_img <br>
</p>
";
?>
The problem is in these lines:
&
These lines, when page=1, will load images from
ID 0toID 6, total 7 images and when page=2, the code will result in$statr_img = ((2-1)*6)+1=7andID 7actually will be 8th image, because we are counting from 0. Same,$last_img = 7+5=12and again,ID 12is the 13th image.UPDATE:
Here is the updated complete code. No need for an if/else . Ofcourse you need to sanitize $_GET.
Results for Page =1,2,3 ($cur_page is 1 or 2 or 3) from above code:
Page=1, Results:
Page=2, Results:
Page=3, Results:
Also, use of
<table>for layouts is strongly discouraged. Please look into CSS & DIVs. Look into this code for implying same design in CSS.So, now your page structure is like:
Of course you need to check out magical
Floatproperty of CSS for eachDiv. I would leave that to you (Google Css Float).