[英]PHP CSV export from stored MySQL Procedure
Trying to use the below code to call a stored procedure on MySQL and export to CSV. 尝试使用以下代码在MySQL上调用存储过程并导出为CSV。 It generates a csv file however it is blank. 它会生成一个csv文件,但是它是空白的。 The stored procedure is called DATAEXPORT1 该存储过程称为DATAEXPORT1
Any ideas would be grateful! 任何想法将不胜感激!
<?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;
?>
Used the following code which works nicely: 使用了下面的代码,效果很好:
<?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();
I only modify little your script 我只修改一点你的脚本
<?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;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.