The Computer Gal Logo - Laptop with coffee and plants
Using a Database and PHP to Get a Random Image
One of my former students says that there are three errors in this code. What do you think?
The Computer Gal on Facebook
Ask to receive tips and handouts to your email.

The following is code and an explanation of the code to place a random image on your website. The code assumes that the information about the images is in a database, and the photos are uploaded to a particular directory on your website. The code also assumes that your database holds the image file name, caption and a URL that goes to a page about the photo topic. The code discusses a logic error to help you understand how code that works in one instance could break.

Note: each line is numbered to correspond with a discussion of the code. The discussion is below the code so you can see the code as it would be laid out in the web page code.

First Programming Step: connect to the database.

2. <?php

3.  $DatabaseConnection =

4.   mysql_connect("YourDatabaseServer","YourUserName","YourPassword");

5.  if (!$DatabaseConnection)

6.   {

7.     die('There was a problem getting the photos: ' . mysql_error());

6.   } // if the database can't connect, provide user feedback

8. else

6. {

9. $Database = mysql_select_db("WhichDatabase ",WhichConnection);

Second Programming Step: Find out how many records are in the database to choose from

10. // Get the highest ID in the database

11. $MaxIDQuery = "SELECT Max(PhotoID) FROM FrontPhotos;";

12. // Test: echo $MaxIDQuery;

13. $MaxIDResult = mysql_query($MaxIDQuery);

14. $MaxArray = mysql_fetch_array($MaxIDResult);

15. $MaxID = $MaxArray['Max(PhotoID)'];

16. // Test: echo $MaxID;

Third Programming Step: Get a random PhotoID

17. // Get one random picture from the database

18. $Rand = rand(1, $MaxID);

19. $PhotoQuery = "SELECT FileName, Caption, URL FROM FrontPhoto WHERE PhotoID = '".$Rand."';";

20. // Test: echo $PhotoQuery;

21. $PhotoResult = mysql_query($PhotoQuery);


Fourth Programming Step: Pull the information out of the recordset

22. $PhotoArray = mysql_fetch_array($PhotoResult);

23. $FileName = $PhotoArray['FileName'];
      $Caption = $PhotoArray['Caption'];
      $URL = $PhotoArray['URL'];

Fifth Programming Step: Close any loops, statements, and PHP that hasn't been closed; so, you can go on to the HTML

6. }

2. ?>

Sixth Programming Step: Use the information in your HTML

24. <?php

25. echo '<a href="'.$URL.'">

26. echo '<img src="Path to your Front Photos/"'.$FileName.'" alt="'.$Caption.'">';

27. echo '</a>';

28. echo '<div class="Your class">'.$Caption.'</div>';

29. ?>

 

Notes about this Code
  1. This code will only work in a file with a .php extension because it has to be interpretted by PHP
  2. <?php and ?> tell PHP what parts of the page need to be interpreted. Some programmers put the entire page in PHP, but the less you put into the <?php ?>, the more a non-programming developer can work on the site. You could infer from that, the a programmer who puts the whole page in PHP is trying to keep other people from working on the page.
    - You can also use <? and ?>
    - You can also use <script language="PHP"></script>. You may recognize this from JavaScript.
  3. $DatabaseConnection =   
    - This is declaring and defining a variable.
    - PHP variables are named with a $ when they are declared and used.
    - The variable is taking the returned value from a function().
  4. mysql_connect("YourDatabaseServer","YourUserName","YourPassword");
    - The function() mysql_connect() is a pre-written function, which is available to PHP from a library.
    - mysql_connect takes three parameters. Each parameter is a string.
  5.  if (!$DatabaseConnection)
    - mysql_connect is a function, which returns a value true or false - the database server did connect or the database server didn't connect
    - the result of that connection was stored in the $DatabaseConnection variable (memory location)
    - since the value is true or false, and ! means false, this if statement will test if the database server connection failed
  6. { statements }
    - just like JavaScript, PHP uses curly braces to hold a group of statements together
    - notice that the closing } has a comment after it
    - PHP comments are marked with // if they are on one line and /* comment */ if they cover two lines.
    - it will save you a lot of time looking for things if you will end each set of curly braces with a comment that tells what it's closing
  7. die('There was a problem getting the photo: ' . mysql_error());
    - this is a function in the PHP library
    - you can find out about what a particular library function does on sites like this
    - the die() function takes one parameter/argument, which is a string describing the error to the viewer. It is best to make these as humanly friendly as possible.
    - this error message concatenates the "There was a problem getting the photo: " with the error returned from MySQL.
    - notice that a period is the concatenation operator
    - notice that there is a space before the : - otherwise the programming would push the messages together with no space.
  8. else
    - an if statement can have an else statement or not
    - if there are more than two options, you can have an elseif statement between the if statement and the else statemet
    - a switch statement is often used when there are a series of possibilities
  9. $Database = mysql_select_db("WhichDatabase ", $WhichConnection);
    - $Database is a variable that
    holds information about which database is the current database
    - mysql_select_db() is the function which makes a certain database the current database
    - mysql_select_db can take two parameters/argument: first is what database you want, the second is optional and passes information about the original connection string.
    - in this case, we have to type in the database name; so, it is shown here in quotes
    - in this case, we have a variable for the WhichConnection; so, it is not shown in quotes
    - the second parameter/argument is needed because you could have more than one database connection on one page
  10. // Get the highest ID in the database
    - use comments throughout your code to help you find areas you want to change without reading the whole page.
    - this is actually a logic error. It assumes that no records have ever been deleted, and so, all the numbers exist. If an ID has been deleted, and the random code chooses that particular number, your programming could fail or show a broken image. To fix this, you either need to have a stock photo that you will use, if the query fails to find the record number it is looking for, or you will have to come up with some other method of getting the records.
  11. $MaxIDQuery = "SELECT Max(PhotoID)FROM FrontPhotos;";
    - the variable $MaxIDQuery will hold the string that is the query. This allows you to isolate the query from all the other code and makes it easier to debug. If you want to find out why your query didn't work, you can set it to echo onto the page and enter it into a program like phpMyAdmin to see what went wrong. (See #12)
    - the SELECT statement doesn't just have to choose fields, there are a number of aggregate functions that can be used. This one picks the highest ID. It could also choose a Count() of the PhotoID, which would result in a more accurate number to choose from.
  12. // Test: echo $MaxIDQuery;
    - every time you need to test the value of a variable on your site, leave the test code on your site, comment it out, and mark it as a Test. Then, if you need to retest later, your tests are there waiting for you.
  13. $MaxIDResult = mysql_query($MaxIDQuery);
    - notice that the variable names clearly reflect what value they hold
    - mysql_query() sends the query string to the database
    - the result will be a recordset, even if there are no records or, if the query fails because the query is created incorrectly, there will be no recordset in the result.
  14. $MaxArray = mysql_fetch_array($MaxIDResult);
    - a recordset is a set of arrays, which are the rows in a database.
    - even if there is only one value, as in this case, you still have to get the data from an array.
    - if the recordset is many rows, you have to fetch an array for each row. This is usually done with a for loop.
    - each time you get another row, the system moves the pointer to the next row in the dataset. That means that the next time you ask for an array, it will be the next row.
  15. $MaxID = $MaxArray['Max(PhotoID)'];
    - the values in an array are inside [].
    - this statement pushes the one value the array holds into a variable called $MaxID.
    - notice that the name of the value is in single quotes
  16. // Test: echo $MaxID;
    - it's always good to have a test of the values that you are taking from a database to use in other programming
  17. // Get one random picture from the database
    - it's always a good idea to make notes about what the code is supposed to do.
  18. $Rand = rand(1, $MaxID);
    - the variable $Rand will hold the value returned from the assignment operation. "In computer science the assignment statement sets or re-sets the value stored in the storage location(s) denoted by a variable name."
    from http://en.wikipedia.org/wiki/Assignment_%28computer_science%29
    - the function is rand(). The specifications for rand are int rand ( int $min , int $max ). In this case, we want rand() to pick a number between 1 and the last PhotoID value, which is being held in $MaxID. See #10 for the logic error in this code.
  19. $PhotoQuery = "SELECT FileName, Caption, URL FROM FrontPhoto WHERE PhotoID = '".$Rand."';";
    -
    this will put the text for the query into a variable, which is easier to read in the code that sends the query
    - this query will get the fields from the database that will be used on the web page: FileName, Caption, and URL
    - this query uses the variable $Rand to decide which photo to select
    - PHP will put the value in for the $Rand
    - notice that the string part is enclosed in " "
    - $Rand is enclosed in both single and double quotes: the single quotes are required for the query, the double quotes are required to close the string; so, PHP can recognize the variable
    - . is the concatenation operator in PHP; the statement says to concatenate the string with the value from $Rand with the ending of the statement
    - there are two semicolons: one closes the MySQL statement and one closes the PHP statement
  20. //echo $PhotoQuery;
    - again, this is a test of the query string, if the $PhotoResult doesn't work. It will print onto the page; so, you can copy it into another application with access to your database, such as PHPMyAdmin.
  21. $PhotoResult = mysql_query($PhotoQuery);
    - the variable $PhotoResult will hold the recordset array returned from the database
    - the recordset is requested with mysql_query
    - the variable $PhotoQuery holds the query text to make this statement easier to read
  22. $PhotoArray = mysql_fetch_array($PhotoResult);
    - same as #14 for the $MaxPhotoID
    - even though there is only one line of information in the recordset, we have to pull the pieces out of the recordset array. The first step is to identify the array.
  23. $FileName = $PhotoArray['FileName']; - etc
    - puts each field from the record into a local variable
    - these variables are now ready for use on the web page
  24. <?php
    - there may be blocks of PHP code anywhere in your code, even inside an HTML tag.
    - the web server runs the PHP and adds the "dynamic" code to the rest of your HTML
  25. echo '<a href="'.$URL.'">
    - the HTML code generated by this PHP statement will actually show up on the same line as #26 because there is no <br>
    - this code makes the image (#26) clickable
    - this assumes that you have the URL entered correctly in the database
  26. echo '<img src="Path to your Front Photos/"'.$FileName.'" alt="'.$Caption.'">';
    - echo is a PHP function to write the next part into the HTML code (write to the page)
    - this echo will produce an <img ...>
    - notice that there are single quotes around the string. HTML uses double quotes; so, can use single quotes for the PHP
    - whenever you need to insert a variable value, you have to close the string. This uses a double quote as part of the HTML and a single quote to close the PHP string; so, the PHP can put the variable value into the string.
    - this statement uses two variables
  27. echo '</a>';
    - this closes the link
    - #25 - 27 could all go on the same echo line, but it makes the code easier to read - and debug - if you split it up
  28. echo '<div class="Your class">'.$Caption.'</div>';
    - adds a caption
    - you can use CSS in your echo statements too
    - you can even write JavaScript in your PHP statements. The resulting JavaScript will be sent to the browser. One example would be if you need to get database information to pass to a Google map. The Google mapping code is JavaScript

Related Information

  1. State/Province Dropdown with Selected
  2. Random Image Generator Code - be sure to read the article carefully for the logic error discussion
  3. When to Use Single and Double Quotes
Nora McDougall | Missoula, Montana 59801 | 406.253.4045 | Contact Nora
© 2010, Nora McDougall-Collins