gpt4 book ai didi

PHP:将 MYSQL 查询写入 CSV

转载 作者:可可西里 更新时间:2023-11-01 07:25:16 25 4
gpt4 key购买 nike

我正在尝试将 MySQLi 查询写入可下载的 CSV。以下 header 打开 CSV 流:

$fileName = ''; //empty file name, file name is cast later
header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen( 'php://output', 'w' );

在此之下,我有以下尝试查询并将查询的每一行转换为 CSV 文件中的新行:

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight')){
$fileName .= 'OutputWeightNull.csv';
$query = mysqli_query($conn, 'SELECT * FROM `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL')or die(mysql_error());
$result = mysqli_fetch_array($query) or die(mysql_error());
$headerDisplayed = false;
foreach ($result as $data){
if (!headerDisplayed){
fputcsv($fh, array_keys());
$headerDisplayed = true;
}
fputcsv($fh, $data);
}
}

CSV 正在按需要下载到浏览器,但它显示为空,查询结果未发送到 CSV。谁能指出我正确的方向,说明为什么会这样。

这是我第一次尝试编写比 hello world 更复杂的 PHP 脚本。如果答案非常简单或显而易见,我们深表歉意。

最佳答案

清理代码以围绕返回的行循环,并使用 mysqli_ 错误函数:-

<?php 

if(isset($_POST["Submit"]) && ($_POST['Weight'] == 'Weight'))
{
$fileName = ''; //empty file name, file name is cast later
header("Cache=Control: must-revalidate, post-check=0, pre-check=0");
header('Content-Description: File Transfer');
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename={$fileName}");
header("Expires: 0");
header("Pragma: public");
$fh = @fopen( 'php://output', 'w' );

$fileName .= 'OutputWeightNull.csv';
$query = mysqli_query($conn, 'SELECT * FROM `Some_Table` WHERE WEIGHT = 0 OR weight IS NULL') or die(mysqli_error($conn));
if ($result = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
fputcsv($fh, array_keys($result));
fputcsv($fh, $result);
while ($result = mysqli_fetch_array($query, MYSQLI_ASSOC))
{
fputcsv($fh, $result);
}
}
}

关于PHP:将 MYSQL 查询写入 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33433737/

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