Random Image Generator
Jump to navigation
Jump to search
On my website I had been using a third party Javascript random image generator which scrolled through my /images folder and displayed a random image. I found this to be an inelegant solution. So I decided to go native, so to speak, and develop a simple solution using MySQL and PHP.
Basically, I have a number of tables in my database, all of which contain a couple of common fields:
• IMAGE - Stores the directory and name of the Image.
• URL - Stores the URL of the page on which the image appears.
I achieved what I wanted with a couple of very simple steps:
Created a View to bring all the IMAGE and URL information into one place:
CREATE OR REPLACE VIEW IMAGE_VW (IMAGE, URL) AS SELECT IMAGE, URL FROM TABLEA UNION SELECT IMAGE, URL FROM TABLEB;
I then implemented the following SQL and PHP code:
<?php $queryx = "SELECT IMAGE, URL FROM IMAGES_VW ORDER BY RAND() LIMIT 1"; $resultx = mysql_query($queryx); while($row = mysql_fetch_row($resultx)) { $IMAGE = $row[0]; $URL = $row[1]; echo "<a href=$URL><img src=$IMAGE></a>"; } ?>