Skip to Main Content
MySQL Cookbook
book

MySQL Cookbook

by Paul DuBois
October 2002
Intermediate to advanced content levelIntermediate to advanced
1024 pages
27h 26m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook

Serving Banner Ads

Problem

You want to display banner ads by choosing images on the fly from a set of images.

Solution

Use a script that selects a random row from an image table and sends the image to the client.

Discussion

The display_image.pl script just shown assumes that the URL contains a parameter that names the image to be sent to the client. Another application might determine which image to display for itself. One popular image-related use for web programming is to serve banner advertisements for display in web pages. A simple way to do this is by means of a script that picks an image at random each time it is invoked. The following Python script, banner.py, shows how to do this, where the “ads” are the flag images in the image table:

#! /usr/bin/python # banner.py - serve randomly chosen banner ad from image table # (sends no response if no image can be found) import sys sys.path.insert (0, "/usr/local/apache/lib/python") import MySQLdb import Cookbook conn = Cookbook.connect ( ) try: query = "SELECT type, data FROM image ORDER BY RAND( ) LIMIT 1" cursor = conn.cursor ( ) cursor.execute (query) row = cursor.fetchone ( ) cursor.close ( ) if row is not None: (type, data) = row # Send image to client, preceded by Content-Type: and # Content-Length: headers. The Expires:, Cache-Control:, and # Pragma: headers help keep browsers from caching the image # and reusing it for sucessive requests for this script. print "Content-Type: %s" % type print "Content-Length: %s" % len (data) ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL Reference Manual

MySQL Reference Manual

Michael Widenius, David Axmark, Kaj Arno
High Performance MySQL

High Performance MySQL

Jeremy D. Zawodny, Derek J. Balling
MySQL Stored Procedure Programming

MySQL Stored Procedure Programming

Guy Harrison, Steven Feuerstein

Publisher Resources

ISBN: 0596001452Catalog PageErrata