从存储的MySQL过程导出PHP CSV

时间:2016-04-19 14:30:21

标签: php mysql csv stored-procedures

尝试使用以下代码在MySQL上调用存储过程并导出为CSV。它会生成一个csv文件,但它是空白的。存储过程称为DATAEXPORT1

任何想法都会感激不尽!

<?php


 $host = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$file = 'export';
$connection = mysqli_connect($host, $username, $password, $dbname) or     die("Connection Error " . mysqli_error($connection));
/*
* execute sql query
*/

$sql = "Call DATAEXPORT1()";

$result = mysqli_query($connection,$sql) or die("Selection Error " . mysqli_error($connection));

if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";

$values = mysqli_query($connection,$sql);
while ($rowr = mysqli_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;
mysqli_close($connection);
exit;
?>

2 个答案:

答案 0 :(得分:2)

使用以下代码可以很好地运行:

 <?php
 $host = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
 $connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));

// fetch mysql table rows
$sql = "CALL DATAEXPORT1()";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));

header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="output1.csv"');

$file = fopen('php://output', 'w');


while($row = mysqli_fetch_assoc($result))
{
    fputcsv($file, $row);
}

fclose($file);

//close the db connection
mysqli_close($connection);
exit();

答案 1 :(得分:0)

我只修改你的剧本

<?php
$host     = "localhost";
$username = "xxx";
$password = "xxx";
$dbname   = "xxx";

$file     = 'export';

$connection = mysqli_connect($host, $username, $password, $dbname) or     die("Connection Error " . mysqli_error($connection));

/*
 * execute sql query
 */

$sql = "Call DATAEXPORT1()";

$result = mysqli_query($connection,$sql) or die("Selection Error " . mysqli_error($connection));

$num_rows = count($result);
$csv_output = '';

if( $num_rows > 0) {
    foreach($result as $item => $value){
        $csv_output .= $item . ", " . $value . "\n";
        $i++;
    }
}


$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;

mysqli_close($connection);

exit;
?>