View Full Version : Little problem in PHP

01-31-2007, 09:04 PM

I am facing a little problem in PHP.

I have a table which has three fields

Table Name : images
field1 Name:img_id
field2 Name :image_path
field3 Name:image_text

The requirement is to show the Image and its respective text in a Table. And show only One image and its text at a time.

Below Table there are two button links, "NEXT" and "PREVIOUS". When user press the "NEXT" button the page
refreshes and it will show the NEXT IMAGE and its respective text. And when user press the PRevious button
it goes onestep back.

Kindly help that how can i do this.

I spend many hours on this, but i am unable to write its algo and sequenced code. I am unable to write the sequence of code.

Kindly help


01-31-2007, 09:57 PM
I think what you're talking about is 'pagination'. If you are then my solution is below:

//Connect to your DB

$imagespp = 1; //Number of images per page

$page = 1;
$page = $_GET['page'];

//Current Page

$startfrom = (($page * $imagespp) - $imagespp);

$cursql = "SELECT * FROM images LIMIT $startfrom, $imagespp";
$curresult = mysql_query($cursql);

while($row = mysql_fetch_array($curresult)){
echo $row['img_id'];
echo '<br/>';
echo $row['img_path'];
echo '<br/>';
echo $row['img_text'];
echo '<br/>';
echo 'Current Page Query Failed';

//Links to other Images

$sql_total = mysql_query("SELECT * FROM images");

$totalimages = mysql_num_rows($sql_total);

$totalpages = ($totalimages / $imagespp);

if($page > 1){
$prev = ($page - 1);
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.$prev.'">PREV</a>';

if($page < $totalpages) {
$next = ($page + 1);
echo '<a href="'.$_SERVER['PHP_SELF'].'?page='.$next.'">NEXT</a>';


01-31-2007, 10:05 PM
I assume the problem you are having is how to make the Next and Previous work, not displaying the image.

The way I'd structure it is have the links have an ID in them. Then make the next link as such:

<a href="image.php?action=next&id=123">Next</a>

At the top of your PHP (image.php) file.

if (isset($_REQUEST['next'])) {
$sql = "SELECT * FROM images WHERE id >= " . $_REQUEST['id'] . " ORDER BY img_id ASC LIMIT 1, 1"; // this gets the row that follows the row with ID specified in the URL
// ... display image etc. ...

You'd do the reverse for the Previous link (WHERE img_id <= id ORDER BY img_id desc LIMIT 1, 1)

To know whether there is a previous or next image, just change the LIMIT to 1, 2. That way if you don't get more than 1 result, there is no next or previous image.