Jump to content

Next and Previous links to display images within a mysql db


jackson5

Recommended Posts

Hi I'm new to PHP and I am trying to solve this problem.

I have created a db in mysql with a table storing file paths for some images stored in a folder within my site.

All I want to do is view the first image and then use previous and next links to view the others.

This code works to view the first image but I cannot see any other images using the next/previous links.

Please can you let me know where I am going wrong? :)

<?php

 

//Connect to the database

mysql_connect("localhost", "root", "") or die(mysql_error());

mysql_select_db("gina_photography");

 

 

//mysql queries

$result = mysql_query("SELECT * from image2 LIMIT 1") or die(mysql_error());

 

// Our sample images and their thumbnail directories

 

$img_dir = 'images/db_test';

 

// Lets check our input and validate it. We only want jpg images

if (preg_match("/\w+\.jpg$/",$_GET['p'])) { $image = $_GET['p']; }

 

// Read the directory and only get images

if ($handle = opendir($img_dir)) {

while (false !== ($filename = readdir($handle))) {

if (preg_match("/\w+\.jpg$/",$filename)) {

$files[] = $filename;

sort($files);

}

}

closedir($handle);

}

 

// If no image was set, we'll make the first image the default

if ($image && file_exists("$img_dir/$image")) {} else { $image = $files[0]; }

 

for ($i=0;$i<count($files);$i++) {

if ($files[$i] == $image) {

$previous = $files[$i-1];

$next = $files[$i+1];

$image = $files[$i];

break;

}

}

?> 

 

 

 

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>Untitled Document</title>

</head>

 

<body>

<?php echo "<img src='$img_dir/$image'>" . "<br/><br/>"; ?>

 

<?php

if (file_exists("$img_dir/$last")) { echo "<a href='image.php?p=$previous'> << Previous Image </a> ¦ "; }

if (file_exists("$img_dir/$next")) { echo "<a href='image.php?p=$next'> next Image >> </a>"; }

?>

</body>

</html>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.