Jump to content

Database tables and fields to csv help


semperfi

Recommended Posts

Hi can anybody help I need to export and download tables from a database into a excel sheet. I have this code and it works what I need is to export specific fields and not just the whole table can anyone help modifying the code to export certain fields within the table please? Here is the code...

<?php
$host = 'localhost';
$user = 'user';
$pass = 'password';
$db = 'qdbname';
$table = 'tablename';
$file = 'export';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$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("SELECT * FROM ".$table."");
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;
?>

Link to comment
Share on other sites

Try this, using a fields array.

 

<?php
$host = 'localhost';
$user = 'user';
$pass = 'password';
$db = 'qdbname';
$table = 'tablename';
$file = 'export';
$fields = array('field1', 'field2', 'field3', 'field4');

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$csv_output .= implode('; ', $fields);
$csv_output .= "; \n";

$values = mysql_query("SELECT ".implode(',', $fields)." FROM ".$table);
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<count($fields);$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;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.