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.
No Comments
No comments yet.
RSS feed for comments on this post. TrackBack URL
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!