Problem Solution Discussion Serving Query Results for Download
17.9.4 See Also
I f you run a version of MySQL older t han 3.23.2, t he ORDER BY RAND clause used in t he im age- select ion query will fail. See Recipe 13.8 for a workaround.17.10 Serving Query Results for Download
17.10.1 Problem
You want t o send dat abase inform at ion t o a browser for downloading rat her t han for display.17.10.2 Solution
Unfort unat ely, t heres no good way t o force a download. A browser will process inform at ion sent t o it according t o t he Content-Type: header value, and if it has a handler for t hat value, it will t reat t he inform at ion accordingly. However, you m ay be able t o t rick t he browser by using a generic cont ent t ype for which it s unlikely t o have a handler.17.10.3 Discussion
Earlier sect ions of t his chapt er discuss how t o incorporat e t he result s of dat abase queries int o web pages, t o display t hem as paragraphs, list s, t ables, or im ages. But what if you want t o produce a query result t hat t he user can download t o a file inst ead? I t s not difficult t o generat e t he response it self: send a Content-Type: header preceding t he inform at ion, such as textplain for plain t ext , imagejpeg for a JPEG im age, or applicationpdf or applicationmsexcel for a PDF or Excel docum ent . Then send a blank line and t he cont ent of t he query result . The problem is t hat t heres no way t o force t he browser t o download t he inform at ion. I f it knows what t o do wit h t he response based on t he cont ent t ype, it will t ry t o handle t he inform at ion as it sees fit . I f it knows how t o display t ext or im ages, it will. I f it t hinks it s supposed t o give a PDF or Excel docum ent t o a PDF viewer or t o Excel, it will. Most browsers allow t he user t o select a download explicit ly for exam ple, by right - clicking or cont rol- clicking on a link , but t hat s a client - side m echanism . You have no access t o it on t he server end. About t he only t hing you can do is t ry t o fool t he browser by faking t he cont ent t ype. The m ost generic t ype is applicationoctet-stream . Most users are unlikely t o have any cont ent handler specified for it , so if you send a response using t hat t ype, it s likely t o t rigger a download by t he browser. The disadvant age of t his, of course, is t hat t he response cont ains a false indicat or about t he t ype of inform at ion it cont ains. You can t ry t o alleviat e t his problem by suggest ing a default filenam e for t he browser t o use when it saves t he file. I f t he filenam e has a suffix indicat ive of t he file t ype, such as .t xt , .j pg, .pdf, or .xls, t hat m ay help t he client or t he operat ing syst em on t he client host det erm ine how t o process t he file. To suggest a nam e, include a Content-Disposition: header in t he response t hat looks like t his: Content-disposition: attachment; filename= suggested_name The follow ing PHP script , download.php, dem onst rat es one way t o produce downloadable cont ent . When first invoked, it present s a page cont aining a link t hat can be select ed t o init iat e t he download. The link point s back t o download.php but includes a download param et er. When you select t he link, it reinvokes t he script , which sees t he param et er and responds by issuing a query, ret rieving a result set , and sending it t o t he browser for downloading. The Content-Type: and Content-Disposition: headers in t he response are set by invoking t he header funct ion. This m ust be done before t he script produces any ot her out put , or header will have no effect . ?php download.php - retrieve result set and send it to user as a download rather than for display in a web page include Cookbook.php; include Cookbook_Webutils.php; title = Result Set Downloading Example; If no download parameter is present, display instruction page if get_param_val download { construct self-referential URL that includes download parameter url = get_self_path . ?download=1; ? html head title?php print title; ?title head body bgcolor=white p Select the following link to commence downloading: a href=?php print url; ?downloada p body html ?php exit ; } end of if The download parameter was present; retrieve a result set and send it to the client as a tab-delimited, newline-terminated document. Use a content type of applicationoctet-stream in an attempt to trigger a download response by the browser, and suggest a default filename of result.txt. conn_id = cookbook_connect ; query = SELECT FROM profile; if result_id = mysql_query query, conn_id die Cannot execute query\n; header Content-Type: applicationoctet-stream; header Content-Disposition: attachment; filename=\result.txt\; while row = mysql_fetch_row result_id print join \t, row . \n; mysql_free_result result_id; mysql_close conn_id; ? download.php uses a couple of funct ions we havent covered yet . get_self_path ret urns t he script s own pat hnam e. This is used t o const ruct a URL t hat point s back t o t he script and t hat includes a download param et er. get_param_val is used t o det erm ine whet her t hat param et er is present . These funct ions are included in t he Cookbook_Webut ils.php file and are discussed furt her in Recipe 18.2 and Recipe 18.6 . Anot her possibilit y for producing downloadable cont ent is t o generat e t he query result , writ e it t o a file on t he server side, com press it , and send t he result t o t he browser. The browser will likely run som e kind of uncom press ut ilit y t o recover t he original file.Chapter 18. Processing Web Input with MySQL
Sect ion 18.1. I nt roduct ion Sect ion 18.2. Creat ing Form s in Script s Sect ion 18.3. Creat ing Single- Pick Form Elem ent s from Dat abase Cont ent Sect ion 18.4. Creat ing Mult iple- Pick Form Elem ent s from Dat abase Cont ent Sect ion 18.5. Loading a Dat abase Record int o a Form Sect ion 18.6. Collect ing Web I nput Sect ion 18.7. Validat ing Web I nput Sect ion 18.8. Using Web I nput t o Const ruct Queries Sect ion 18.9. Processing File Uploads Sect ion 18.10. Perform ing Searches and Present ing t he Result s Sect ion 18.11. Generat ing Previous- Page and Next - Page Links Sect ion 18.12. Generat ing Click t o Sort Table Headings Sect ion 18.13. Web Page Access Count ing Sect ion 18.14. Web Page Access Logging Sect ion 18.15. Using MySQL for Apache LoggingParts
» 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