Problem Solution Discussion Serving Banner Ads
17.9 Serving Banner Ads
17.9.1 Problem
You want t o display banner ads by choosing im ages on t he fly from a set of im ages.17.9.2 Solution
Use a script t hat select s a random row from an im age t able and sends t he im age t o t he client .17.9.3 Discussion
The display_im age.pl script j ust shown assum es t hat t he URL cont ains a param et er t hat nam es t he im age t o be sent t o t he client . Anot her applicat ion m ight det erm ine which im age t o display for it self. One popular im age- relat ed use for web program m ing is t o serve banner advert isem ent s for display in web pages. A sim ple way t o do t his is by m eans of a script t hat picks an im age at random each t im e it is invoked. The following Pyt hon script , banner.py, shows how t o do t his, where t he ads are t he flag im ages in t he image t able: usrbinpython banner.py - server randomly chosen banner ad from image table sends no response if no image can be found import sys sys.path.insert 0, usrlocalapachelibpython 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 print Expires: Sat, 01 Jan 2000 00:00:00 GMT print Cache-Control: no-cache print Pragma: no-cache print print data except MySQLdb.Error, e: pass conn.close banner.py sends a few headers in addit ion t o t he usual Content-Type: and Content-Length: headers. The ext ra headers help keep browsers from caching t he im age. Expires: specifies a dat e in t he past t o t ell t he browser t hat t he im age is out of dat e. The Cache-Control: and Pragma: headers t ell t he browser not t o cache t he im age. The script sends bot h headers because som e browsers underst and one, and som e t he ot her. Why suppress caching? Because if you dont , t he browser will send a request for banner.py only t he first t im e it sees it in a link. On subsequent request s for t he script , t he brower will reuse t he im age, which rat her defeat s t he int ent of having each such link resolve t o a random ly chosen im age. I nst all t he banner.py script in your cgi-bin direct ory. Then, t o place a banner in a web page, use an img t ag t hat invokes t he script . For exam ple, if t he script is inst alled as cgi- bin banner.py, t he following page references it t o include an im age below t he int roduct ory paragraph: -- bannertest1.html - page with single link to banner-ad script -- html head titleBanner Ad Test Page 1title head body bgcolor=white pYou should see an image below this paragraph.p img src=cgi-binbanner.py body html I f you request t his page, it should display an im age, and you should see a succession of random ly chosen im ages each t im e you reload t he page. I am assum ing here t hat you have loaded several im ages int o t he image t able by now using t he load_im age.pl script discussed in Recipe 17.7 . Ot herwise you m ay not see any im ages at all I f you m odify banner.py not t o send t he cache- relat ed headers, you likely will see t he sam e im age each t im e you reload t he page. The cache- cont rol headers suppress caching for links t o bannery.py t hat occur over t he course of successive page request s. Anot her com plicat ion occurs if m ult iple links t o t he script occur w it hin t he sam e page. The following page illust rat es what happens: -- bannertest2.html - page with multiple links to banner-ad script -- html head titleBanner Ad Test Page 2title head body bgcolor=white pYou should see two images below this paragraph, and they probably will be the same.p img src=cgi-binbanner.py img src=cgi-binbanner.py pYou should see two images below this paragraph, and they probably will be different.p img src=cgi-binbanner.py?image1 img src=cgi-binbanner.py?image2 body html The first t wo links t o banner.py are ident ical. What youll probably find when you request t his page is t hat your browser will not ice t hat fact , send only a single request t o t he web server, and use t he im age t hat is ret urned where bot h links appear in t he page. As a result , t he first t w o im ages displayed in t he page will be ident ical. The second t wo links t o banner.py show how t o solve t his problem . The links include som e ext ra fluff at t he end of t he URLs t hat m ake t hem look different . banner.py doesnt use t hat inform at ion at all, but m aking t he links look different fools t he browser int o sending t wo im age request s. The result is t hat t he second t wo im ages will differ from each ot her—unless banner.py happens t o random ly select t he sam e im age bot h t im es, of course.17.9.4 See Also
Parts
» O'Reilly-MySQL.Cookbook.eBook-iNTENSiTY. 4810KB Mar 29 2010 05:03:43 AM
» Introduction Using the mysql Client Program
» Problem Solution Discussion Setting Up a MySQL User Account
» Problem Solution Discussion Starting and Terminating mysql
» Problem Solution Discussion Specifying Connection Parameters by Using Option Files
» Problem Solution Discussion Mixing Command-Line and Option File Parameters
» Problem Solution Discussion What to Do if mysql Cannot Be Found
» Problem Solution Discussion Setting Environment Variables
» Problem Solution Discussion Repeating and Editing Queries
» Problem Solution Discussion Preventing Query Output from Scrolling off the Screen
» Problem Solution Discussion Specifying Arbitrary Output Column Delimiters
» Problem Solution Discussion Logging Interactive mysql Sessions
» Discussion Using mysql as a Calculator
» Writing Shell Scripts Under Unix
» Writing Shell Scripts Under Windows
» MySQL Client Application Programming Interfaces
» Perl Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» PHP Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Python Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Java Connecting to the MySQL Server, Selecting a Database, and Disconnecting
» Problem Solution Discussion Checking for Errors
» Python Java Checking for Errors
» Problem Solution Discussion Writing Library Files
» Python Writing Library Files
» SQL Statement Categories Issuing Queries and Retrieving Results
» Perl Issuing Queries and Retrieving Results
» Python Issuing Queries and Retrieving Results
» Java Issuing Queries and Retrieving Results
» Problem Solution Discussion Moving Around Within a Result Set
» Problem Solution Discussion Using Prepared Statements and Placeholders in Queries
» Perl Using Prepared Statements and Placeholders in Queries
» PHP Python Java Using Prepared Statements and Placeholders in Queries
» Problem Solution Discussion Including Special Characters and NULL Values in Queries
» Perl Including Special Characters and NULL Values in Queries
» PHP Including Special Characters and NULL Values in Queries
» Python Java Including Special Characters and NULL Values in Queries
» PHP Python Java Handling NULL Values in Result Sets
» Problem Solution Discussion Writing an Object-Oriented MySQL Interface for PHP
» Class Overview Writing an Object-Oriented MySQL Interface for PHP
» Connecting and Disconnecting Writing an Object-Oriented MySQL Interface for PHP
» Error Handling Issuing Queries and Processing the Results
» Quoting and Placeholder Support
» Problem Solution Discussion Ways of Obtaining Connection Parameters
» Getting Parameters from the Command Line
» Getting Parameters from Option Files
» Conclusion and Words of Advice
» Problem Solution Discussion Avoiding Output Column Order Problems When Writing Programs
» Problem Solution Discussion Using Column Aliases to Make Programs Easier to Write
» Problem Solution Discussion Selecting a Result Set into an Existing Table
» Problem Solution Discussion Creating a Destination Table on the Fly from a Result Set
» Problem Solution Discussion Moving Records Between Tables Safely
» Problem Solution Discussion Cloning a Table Exactly
» Problem Solution Discussion Generating Unique Table Names
» Problem Solution Discussion Using TIMESTAMP Values
» Problem Solution Discussion Using ORDER BY to Sort Query Results
» Solution Discussion Working with Per-Group and Overall Summary Values Simultaneously
» Problem Solution Discussion Changing a Column Definition or Name
» Problem Solution Discussion Changing a Table Type
» Problem Solution Discussion Adding Indexes
» Introduction Obtaining and Using Metadata
» Problem Solution Discussion Perl PHP
» Problem Solution Discussion Perl
» PHP Obtaining Result Set Metadata
» Python Obtaining Result Set Metadata
» Java Obtaining Result Set Metadata
» Using Result Set Metadata to Get Table Structure
» Problem Solution Discussion Database-Independent Methods of Obtaining Table Information
» Problem Solution Discussion Displaying Column Lists Interactive Record Editing
» Mapping Column Types onto Web Page Elements Adding Elements to ENUM or SET Column Definitions
» Selecting All Except Certain Columns
» Problem Solution Discussion Listing Tables and Databases
» Problem Solution Writing Applications That Adapt to the MySQL Server Version
» Discussion Writing Applications That Adapt to the MySQL Server Version
» Problem Solution Discussion Determining Which Table Types the Server Supports
» General Import and Export Issues
» Problem Solution Discussion Importing Data with LOAD DATA and mysqlimport
» Problem Solution Discussion Specifying the Datafile Location
» Problem Solution Discussion Specifying the Datafile Format
» Problem Solution Discussion Dealing with Quotes and Special Characters
» Problem Solution Discussion Handling Duplicate Index Values
» Problem Solution Discussion Getting LOAD DATA to Cough Up More Information
» Problem Solution Discussion Dont Assume LOAD DATA Knows More than It Does
» Problem Solution Discussion Skipping Datafile Columns
» Problem Solution Discussion Exporting Query Results from MySQL
» Using the mysql Client to Export Data
» Problem Solution Discussion Exporting Tables as Raw Data
» Problem Solution Discussion Exporting Table Contents or Definitions in SQL Format
» Problem Solution Discussion Copying Tables or Databases to Another Server
» Problem Solution Discussion Writing Your Own Export Programs
» Problem Solution Discussion Converting Datafiles from One Format to Another
» Problem Solution Discussion Extracting and Rearranging Datafile Columns
» Problem Solution Discussion Validating and Transforming Data
» Writing an Input-Processing Loop Putting Common Tests in Libraries
» Problem Solution Discussion Validation by Pattern Matching
» Problem Solution Discussion Using Patterns to Match Numeric Values
» Problem Solution Discussion Using Patterns to Match Dates or Times
» See Also Using Patterns to Match Dates or Times
» Problem Solution Discussion Using Patterns to Match Email Addresses and URLs
» Problem Solution Discussion Validation Using Table Metadata
» Problem Solution Discussion Issue Individual Queries Construct a Hash from the Entire Lookup Table
» Use a Hash as a Cache of Already-Seen Lookup Values
» Problem Solution Discussion Converting Two-Digit Year Values to Four-Digit Form
» Problem Solution Discussion Performing Validity Checking on Date or Time Subparts
» Problem Solution Discussion Writing Date-Processing Utilities
» Problem Solution Discussion Performing Date Conversion Using SQL
» Problem Solution Discussion Guessing Table Structure from a Datafile
» Problem Solution Discussion A LOAD DATA Diagnostic Utility
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Access
» Problem Solution Discussion Exchanging Data Between MySQL and Microsoft Excel
» Problem Solution Discussion Exchanging Data Between MySQL and FileMaker Pro
» Problem Solution Discussion Importing XML into MySQL
» Epilog Importing and Exporting Data
» Introduction Generating and Using Sequences
» Problem Solution Discussion Using AUTO_INCREMENT To Set Up a Sequence Column
» Problem Solution Discussion Choosing the Type for a Sequence Column
» Problem Solution Discussion Ensuring That Rows Are Renumbered in a Particular Order
» Problem Solution Discussion Managing Multiple Simultaneous AUTO_INCREMENT Values
» Problem Solution Discussion Using AUTO_INCREMENT Values to Relate Tables
» Problem Solution Discussion Generating Repeating Sequences
» Problem Solution Discussion See Also
» Performing a Related-Table Update Using Table Replacement
» Performing a Related-Table Update by Writing a Program
» Performing a Multiple-Table Delete by Writing a Program
» Problem Solution Discussion Dealing with Duplicates at Record-Creation Time
» Problem Solution Discussion Using Transactions in Perl Programs
» Problem Solution Discussion Using Transactions in Java Programs
» Problem Solution Discussion Using Alternatives to Transactions
» Grouping Statements Using Locks
» Rewriting Queries to Avoid Transactions
» Introduction Introduction to MySQL on the Web
» Problem Solution Discussion Basic Web Page Generation
» Problem Solution Discussion Using Apache to Run Web Scripts
» Problem Solution Discussion Using Tomcat to Run Web Scripts
» Installing the mcb Application
» Installing the JSTL Distribution
» Problem Solution Discussion Encoding Special Characters in Web Output
» General Encoding Principles Encoding Special Characters in Web Output
» Encoding Special Characters Using Web APIs
» Introduction Incorporating Query Results into Web Pages
» Problem Solution Discussion Creating a Navigation Index from Database Content
» Creating a Multiple-Page Navigation Index
» Problem Solution Discussion Storing Images or Other Binary Data
» Storing Images with LOAD_FILE Storing Images Using a Script
» Problem Solution Discussion Retrieving Images or Other Binary Data
» Problem Solution Discussion Serving Banner Ads
» Problem Solution Discussion Serving Query Results for Download
» Introduction Processing Web Input with MySQL
» Problem Solution Discussion Creating Forms in Scripts
» Problem Solution Discussion Creating Multiple-Pick Form Elements from Database Content
» Problem Solution Discussion Loading a Database Record into a Form
» Problem Solution Discussion Collecting Web Input
» Web Input Extraction Conventions Perl
» Problem Solution Discussion Validating Web Input
» Problem Solution Discussion Using Web Input to Construct Queries
» Problem Solution Discussion Processing File Uploads
» Perl Processing File Uploads
» Problem Solution Discussion Performing Searches and Presenting the Results
» Problem Solution Discussion Generating Previous-Page and Next-Page Links
» Paged Displays with Previous-Page and Next-Page Links
» Paged Displays with Links to Each Page
» Problem Solution Discussion Web Page Access Counting
» Problem Solution Discussion Web Page Access Logging
» Problem Solution Discussion Setting Up Database Logging
» Other Logging Issues Using MySQL for Apache Logging
» Session Management Issues Introduction
» Problem Solution Discussion Installing Apache::Session
» The Apache::Session Interface
» A Sample Application Using MySQL-Based Sessions in Perl Applications
» Problem Solution Discussion The PHP 4 Session Management Interface
» Specifying a User-Defined Storage Module
» Problem Solution Discussion Using MySQL for Session BackingStore with Tomcat
» The Servlet and JSP Session Interface A Sample JSP Session Application
Show more