gpt4 book ai didi

php - 使用文件下载将数据从数据库导出到csv

转载 作者:行者123 更新时间:2023-11-30 00:09:00 25 4
gpt4 key购买 nike

我想将数据从数据库导出为csv格式。

我正在使用的代码是(页面名称-export.php)

<?php

// Database Connection

$host = "localhost";
$uname = "root";
$pass = "";
$database = "a2zwebhelp";

$connection = mysql_connect($host, $uname, $pass);

echo mysql_error();

//or die("Database Connection Failed");
$selectdb = mysql_select_db($database) or
die("Database could not be selected");
$result = mysql_select_db($database) or die("database cannot be selected <br>");

// Fetch Record from Database

$output = "";
$table = ""; // Enter Your Table Name
$sql = mysql_query("select * from $table");
$columns_total = mysql_num_fields($sql);

// Get The Field Name

for($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($sql, $i);
$output .= '"' . $heading . '",';
}
$output .="\n";

// Get Records from the table

while($row = mysql_fetch_array($sql))
{
for($i = 0; $i < $columns_total; $i++)
{
$output .='"' . $row["$i"] . '",';
}
$output .="\n";
}

// Download the file

$filename = "myFile.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename=' . $filename);

echo $output;
exit;
?>


它工作正常,但是我希望可以在用户端显示另一个页面,他可以通过单击按钮来下载文件。为此,我正在使用的代码是

<form action="export.php" method="post">
Please click here to download:
<input type="button" name="Download" value="Download">
</form>


我认为我做错了事,因为两个页面没有相互链接。每当我单击下载按钮时,它都会保留在同一页面上。可以请别人指出错误。

最佳答案

问题是您从不提交表单,因此操作从未得到执行。

这是下载页面的外观:

<form action="export.php" method="post">
Please click here to download:
<input type="submit" value="Download">
</form>


我还建议您将MIME类型从 'application/csv'更改为 'text/csv'

关于php - 使用文件下载将数据从数据库导出到csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24242851/

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