Niall Harkiss
Niall Harkiss

Reputation: 3

Randomly select image an from directory using php and use its filename for a mysql query

I have a directory of images which are all named *.jpg, where * is the ID of each record in a MySQL table. e.g. 1394.jpg

What I'd like to be able to do is pull 5 random images from that directory using PHP and for each image, then query the MySQL table for records matching that ID / image filename, so I can then display details of each record.

The part I am looking for some guidance on is how to a) randomly choose 5 images using php, then b) identifying the filenames. Once I have the filename as a variable, I am sure I should be able to write the MySQL query. It's the PHP element I'm struggling with.

Could anyone offer any advice?

Upvotes: 0

Views: 616

Answers (3)

Ulver
Ulver

Reputation: 905

If the file info in your db is update-to-date regarding the image files in your file system, you can get the 5 random filename ids along with other info directly from the db:

$sql = 'SELECT * FROM image_files ORDER BY RAND() LIMIT 5';

This will return you file ids along with other info you have there in the table.

EDIT: Apparently all files in db does not exist in file system. So below is updated answer:

// Get files info from db in random order
$sql = 'SELECT * FROM image_files ORDER BY RAND()';
$result = $conn->query($sql);

// Pick first 5 files that does exist in file system
$five_files=Array();
while($row = $result->fetch_assoc()) {
  $filepath = '/dir/images/'.$row['id'].'.jpg';
  if (is_file($filepath)) {
      $five_files[] = $row;
      if (count($five_files) == 5) break;
  } 
}

// This will have info on five randomly picked files from db that does exist
print_r($five_files);

Upvotes: 1

Sanjeev Sarkar
Sanjeev Sarkar

Reputation: 41

Okay, We will do it in these steps :

  1. Get File Name Lists from the required Directory

Function : scandir() look for more details here

  1. Store in Array

  2. Get Random 5 Data

Function array_rand() look for more details here

  1. For Each File Run Query For Details

Loop - Foreach() - Store MySQL-fetched-data in multi-dimensional Array

  1. Display

Upvotes: 0

iJos
iJos

Reputation: 86

I'll do that, first getting all the images of the folder

$files = glob("$dir/*.{jpg,jpeg}", GLOB_BRACE);

Then, I'll get one (you can make a loop) random pic using array_rand, like this

$file = array_rand($files); // You can check if is repeated or something too

Finally, you can preg_replace the name of the file to get only the name (without extension) and query to your DB with that name... (Maybe there are other ways, but this is simple and fast)

Upvotes: 1

Related Questions