Note: Technical Talk being moved to:
www.nazimcricket.com/wiki


Saturday, 1 November 2008

Random Image Generator

On my website I have been using a third party PHP random image generator which scrolls through my /images folder and displays a random image.

This has been working fine except that my images are stored in multiple folders and as a result I've been missing out on displaying quite a few of these. Also, I don't have any control in terms of turning the random image returned into a hyperlink to the page containing it etc.

To solve this problem, I decided I would use the power of SQL to return a random image, rather than use 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 was after in 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;
    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>";
    
    }
    
    ?>
  • No comments: