Adding 1-5 images with PHP


What is the best way to add 1-5 images using PHP? Some pages need 3 images, others 5 images and other pages only need 1 but it is never more than 5 images per page.

If I have fields for images 1 to 5 in a MySQL table then I use PHP to get these 5 images then if there are only 3 images then there are two errors on the page indicating where the further 2 images should/would be.

I thought maybe there was a way to code the page to say ‘if the entry in the MySQL table is blank, then do not add this bit of code’. Or, even better, can PHP code check to see what images are on the server - ie. it if it only finds product1image01, product1image02, product1image03 it only includes 3 images. If it only finds product2image01 then it only includes 1 image, etc.???

This must be a common problem. How should I get around this problem?


How are you currently doing it Matt? Please use [ php ][ /php ] (remove the spaces) when posting code

if ($row['image4'] == '')

Something like that?

But I think you should normalize your database.
Instead of having 5 columns in your pages table (image1, image2, image3, image4, image5) create a new table (pageimages or whatever) with two columns:

If a page contains 2 images, then this table will have two rows with that pageid.
If a page contains 5 images, then this table will have five rows with that pageid.

Now all you have to do is get the rows for the pageid you want to show, and loop through the mysql result set.

Yes, I suppose you mean by

if ($row['image4'] == '')  

that this means if it is blank do nothing. ie. the ‘else’ statement would be to add the image, right?

I will consider your second suggestion.