Skip to Content
MySQL Cookbook, 2nd Edition
book

MySQL Cookbook, 2nd Edition

by Paul DuBois
November 2006
Intermediate to advanced
977 pages
30h 42m
English
O'Reilly Media, Inc.
Content preview from MySQL Cookbook, 2nd Edition

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 shown in Retrieving Images or Other Binary Data 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 MySQLdb import Cookbook conn = Cookbook.connect () stmt = "SELECT type, data FROM image ORDER BY RAND() LIMIT 1" cursor = conn.cursor () cursor.execute (stmt) 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 successive requests for this script. print "Content-Type: %s" % type print "Content-Length: %s" % len (data) print "Expires: Sat, 01 Jan 2000 00:00:00 ...
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 Cookbook, 3rd Edition

MySQL Cookbook, 3rd Edition

Paul DuBois
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
MySQL Cookbook

MySQL Cookbook

Paul DuBois
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal

Publisher Resources

ISBN: 059652708XSupplemental ContentErrata Page