Jump to content

[SOLVED] Please help : MYSQL to EXCEL Converter.


cuboidgraphix

Recommended Posts

Greetings,

 

I'm having some problems with my MYSQL to EXCEL conversion script. The script works fine in getting the data and converting it into excel, the problem I'm having is that I want to include the mysql field names into the excel file. 

 

The script goes as follows.

 

<?php
$db = @$_POST['db'];
$date = @$_POST['date'];
$query = @$_POST['query'];
$file = @$_POST['file'];

mysql_connect("localhost","user","pass"); 
mysql_select_db("$db") or die("Unable to select database"); 

$result = mysql_query("$query") or die('Error, query failed');

// This part for the field names
while ($i < mysql_num_fields ($result)) 
{
$meta = mysql_fetch_field ($result);
}


// This part for the data
$tab = array();
$html = array();
while($row = mysql_fetch_array($result, MYSQL_NUM))
{
$tab[]  = implode("\t", $row);
$html[] = "<tr><td>" .implode("</td><td>", $row) . "</td></tr>";
}

$tab  = implode("\r\n", $tab);
$html = "<table>" . implode("\r\n", $html) . "</table>";

header("Content-type: application/vnd.ms-excel"); 
header("Content-Disposition: attachment; filename=$date-$file.xls");

echo $meta();
echo $html;
?>

 

Any help would be greatly appreciated.

Thanks.

<?php
include 'db.php';    //connnection stuff

function xlData($query, &$meta, &$data) {
    $result = mysql_query($query);

    // column headings
          while ($fld = mysql_fetch_field ($result)) {
                   $meta[] = $fld->name;
          }

    // data
          while ($row = mysql_fetch_row($result)) {
              $data[] = $row;
          }
}

//
// call function
//
$date = '2008-04-03';
$file = 'mydata';
$query = "select * from tablename";

$meta =  $data = array();
xlData($query, $meta, $data);

header("Content-type: application/vnd.ms-excel"); 
header("Content-Disposition: attachment; filename=$date-$file.xls");

echo join ("\t", $meta) . "\r\n";
foreach ($data as $row)
{
    echo join ("\t", $row) . "\r\n";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.