gpt4 book ai didi

从存储的 MySQL 过程中导出 PHP CSV

转载 作者:行者123 更新时间:2023-11-29 07:19:26 26 4
gpt4 key购买 nike

尝试使用以下代码调用 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;
?>

最佳答案

使用了以下代码,效果很好:

 <?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();

关于从存储的 MySQL 过程中导出 PHP CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36721418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com