PHP / MySQL – Strip Content And Only Display Images From A MySQL Table
This is another one of those quite specific pieces of code, so I doubt many people will need it. I think the code is quite useful, so I thought i’d make a post about it. Anyways, I’m going to show you how you can pull just images out of a field in a MySQL table. I used this code yesterday, to specifically pull out all images from a WordPress Blog – to look at all the images that have been posted in ALL articles.
What the following PHP/MySQL code will specifcally deliver…
- It will pull out ONLY images
- If one field has multiple images, it will display ALL of them
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //this query will only get the rows that have images in them $sql = "SELECT [field] FROM [table] WHERE [field] LIKE '%<img src="; //execute the query $result = mysql_query($sql); //loop the results while($row = mysql_fetch_array($result)) { //this is the magic - preg_match matches all the images saves them into an array called images[] preg_match_all('/<img[^>]+>/i',$row['ENTER FIELD'],$images[]); } //echo out all the images print_r($images); |
That’s it! The print_r will show you all the images when you load the page. The preg_match_all line can actually be used with any string to pull out image references (or whatever regulat expression you require). I’m just specifcially demonstrating how I used it with WordPress/images.
If you don’t want to see the images, and just want to see the actual image URL’s, you can do the following…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | //put the images[] array into a foreach loop foreach($images as $image) { //because each entry may have multiple images, we have to loop through each row to get each image foreach($image[0] as $img) { //remove the <img> tag $img = str_replace('<img src="','', $img); //explode each image by double quotes (or single quotes depending on how you quote your images), so we know where the image URL ends! $img = explode('" ', $img); //rename the image URL to $file for ease $file = $img[0]; //echo out each image URL echo $file . "<br />";; } } |
Please let mw know if anyone actually uses this code and how useful it was…



brightcherry.co.uk
I’ve searching to many tutorial finally i found your post. Its really helpful.
I have one question. How about I just need only one?
Jerwin, you could do LIMIT 1 at the end of the mysql query, or otherwise just add a line after your loop
echo $images[0];
and use echo array_rand($images) ;
to pick a random one.
I am website designer too, enjoyed reading your blog posts ( I work for Infinite Eye http://www.infinite-eye.com in Glasgow, UK).
What if you wanted to do the opposite and echo text without images?
@Jason
You could use the strip_tags function