Reputation: 805
I have a folder unit_images
that is full of images with random names except they have a prefix that corresponds to a PRIMARY KEY
in a db table.
1_4534534fw4.jpg
2_43534tw4t45.png
You get my point. I am using YoxView to view images and am doing something like this:
<?php
$query = "SELECT id FROM images WHERE unit = ".$_GET['id']."";
$result = mysqli_query($con, $query);
echo '<div class="yoxview">';
while ($row = mysqli_fetch_assoc($result))
{
echo '<img src="unit_images/01.jpg" alt="First" title="First image" />
<img src="unit_images/02.jpg" alt="Second" title="Second image" />'
}
echo '</div>';
?>
I want to list the images from my folder unit_images
WHERE the unit is the one currently being shown.I just do not know how to tell PHP the filename. I want to do something similar to a 1_%
in SQL. Does that make sense? Since I do not know what the rest of the filename looks like I just need to tell php it doesn't matter.
Upvotes: 0
Views: 81
Reputation: 3241
If I understand you correctly, you want to get a list of items in a directory with a certain prefix.
Step 1 (use sandir()
to determine the items in the directory):
$files = scandir('unit_images');
Step 2 (eliminate the unwanted image names):
for ($i=0; $i<count($files); i++)
{
$file = $files[i];
$prefix = explode("_", $file)[0];
if ($prefix != $_GET['id'])
{
unset($files[i]);
}
}
$files
is now an array of only the file names prefixed with $_GET['id]
Upvotes: 1
Reputation: 43434
My advice would be to store the whole name of the file in a column so that you can reference it directly instead of having to search in the file system for a matching name.
Having said that, you can search for a file using the glob
PHP function.
Maybe you can do something like this:
glob("unit_images/<YOUR_PRIMARY_KEY>_*.{png,jpg}", GLOB_BRACE);
Upvotes: 0
Reputation: 4502
The closest equivalent to SQL's %
wildcard that works for files is the shell's *
wildcard, which is available in php through the glob()
function. You can iterate through its results as follows:
foreach (glob("unit_images/1_*.jpg") as $filename) {
echo '<img src="unit_images/' . htmlspecialchars(basename($filename))
. '" />';
}
Upvotes: 1