TeamPhotoshop
Reviews, updates and in depth guides to your favourite mobile games - AppGamer.com
Forum Home Latest Posts Search Help Subscribe

PHP Script Needed -- HELP!!

Page: 1 2 Reply
Jul 25th 2002#60658 Report
Member since: Apr 1st 2002
Posts: 1487
Reply with Quote Reply
Nov 27th 2003#130733 Report
Member since: Nov 6th 2001
Posts: 240
I know this post is a bit outdated but maybe someone could use this, it's a function to export data from a MySQL database to excel.

well here it goes:

here's the function that does all the hard work, the connection to the database is included in this function, if you would use this function it is obvious that you put these vars in an external file.

[PHP]
/*
accepts SELECT query
returns data in table according to SELECT query
*/
function export($query) {
$mysql_host = ""; /* your host */
$mysql_user = ""; /* mysql user */
$mysql_password = ""; /* mysql password */

// connect to the server
mysql_connect($mysql_host, $mysql_user, $mysql_password);

// select db
mysql_select_db(""); /* select database */

// execute query
$result_id = mysql_query($query);
// get number of field names
$num_fields = mysql_num_fields($result_id);

// build field names string
for ($i = 0; $i < $num_fields; $i++) {
$field_names .= mysql_field_name($result_id, $i) . "\t";
}
$field_names .= "\n";

// looping through the data
while($row = mysql_fetch_array($result_id, MYSQL_ASSOC)) {
// init row
$line = "";
// getting the value of each row
foreach($row as $value) {
// if the value is empty or not set -> tab
if ((!isset($value)) || ($value == "")) {
$value = "\t";
} else {
// else add the value to the line
$value = str_replace('"', '""', $value);
$value = '"' . $value . '"' . "\t";
}
// build data row
$line .= $value;
}
// build data
$data .= trim($line)."\n";
}

// remove return char
$data = str_replace("\r","",$data);

// no data found -> empty table
if ($data == "") {
$data = "\n(0) Records Found!\n";
}

// finally return data
return $field_names.$data;
}
[/PHP]

now how to call this function...

[PHP]
// calling the function
$export_data = export("SELECT column or * FROM table");
// name of file
$filename = "export_data";
[/PHP]

and the most important thing, the headers to set so the browser will save it as an excel file:

[PHP]
// setting the header, so browser saves as it excel file
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$export_data";
[/PHP]
Reply with Quote Reply
Page: 1 2 Back to top
Please login or register above to post in this forum