This is a quick snippet of code I created to dynamically pull a user-defined query from a MySQL database.
<?php include ('inc/connect.php'); //define the table that you want to pull data from $table = "table_name"; //define the variables for your query $query_variables = $_POST['id']; //build your dynamic query $query = "SELECT * FROM `".$table."` WHERE ".$query_variables.""; $result = mysql_query("SHOW COLUMNS FROM ".$table.""); $i = 0; if (mysql_num_rows($result) > 0) { while ($row = mysql_fetch_assoc($result)) { $csv_output .= $row['Field'].", "; $i++; } } $csv_output .= "\n"; $values = mysql_query("$query"); while ($rowr = mysql_fetch_row($values)) { for ($j=0;$j<$i;$j++) { $csv_output .= $rowr[$j].", "; } $csv_output .= "\n"; } $filename = $file."_".date("Y-m-d_H-i",time()); header("Content-type: application/vnd.ms-excel"); header("Content-disposition: csv" . date("Y-m-d") . ".csv"); header( "Content-disposition: filename=".$filename.".csv"); print $csv_output; exit; ?>
Posted on January 28, 2010 in PHP Tutorials and has been tagged as excel, mysql, php.
1 Comment
My name is Andy Weigel and I'm a web developer and designer in Pittsburgh, PA.
I focus on combining design with technology to build compelling, creative, easy-to-navigate web sites and custom web applications for organizations and businesses of all shapes and sizes. My specialty is WordPress. And most of all, I love what I do!
Great script. How would this script be modified so that the csv file is saved to a location on the host server, and not downloaded through the browser?
Comment by Gavin — November 4, 2010 @ 1:30 pm
RSS feed for comments on this post. TrackBack URL
Leave a comment