Reputation: 3
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
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
Reputation: 41
Okay, We will do it in these steps :
Function :
scandir()
look for more details here
Store in Array
Get Random 5 Data
Function
array_rand()
look for more details here
Loop - Foreach() - Store MySQL-fetched-data in multi-dimensional Array
Upvotes: 0
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