Simple random image rotation May10 '05

For e–commerce sites especially, it’s often smart to showcase images of your products.

But images take up a lot of screen space, so it’s wise to use an "animated gif," or a series of images that rotate, each time the page reloads.

"Animated gif" no more

I usually shy away from using "animated gifs," simply because they are often large files, and take long to load, even on a broadband connection.

Image rotater

A smarter approach would have a single image change, each time the page is loaded. In other words, a random image is generated of the specific product line.

Image information in database

All of my product images are stored in a single FTP folder. Then, with a database, I specify each piece of information, for every image.

An example image file looks like this:

318.jpg

In the database, I use the image number (318) as it’s corresponding table ID. The database table looks something like this:

ID Extension Width Height Alt Text Web Title
318 jpg 128 96 Nokia 6800 Nokia 6800 cell phone, with flip–out keypad

Query to generate our random image

Here is a sample query that would pull out all images of 'Nokia' cell phone models, in random order:

SELECT id, extension, width, height, alt_text, web_title
FROM image_index
WHERE web_title LIKE '%Nokia%'
ORDER BY RAND() LIMIT 1;

This query only pulls out one result, but a random one. So, each time this query is run (each time the page loads), a new image will result.

Thanks to the MySQL function, RAND() (More » Joshua Street), and the LIMIT clause, we can successfully generate a different image on each page load.

PHP to output our results

At this point, you could do anything you wish, with the result set. Below is an example of how the image is output to the browser, with PHP.

$img_src = "<img src=\"/images/".$result_row['id'].".".$result_row['extension']."\"
alt=\"".$result_row['alt_text']."\"
title=\"".$result_row['web_title']."\" />";

echo $img_src;

Categories: PHP , SQL , Tutorials

Add Feedback (view all)

Leave feedback

Feedback

Input format: The editor controls below will assist with Markdown syntax.

Status

Sub-status

Your info

matthom is published and produced by Matt Thommes - an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.

Contact Matt

Similar Entries

Stats

10 unique visits since December 2008

Syndicate

Advertisements