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

时间:2014-06-16 11:37:56

标签: php html mysql sql csv

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

我正在使用的代码是(page name-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>

我认为我做错了,因为这两页并没有相互联系。每当我点击下载按钮时,它都会保留在同一页面上。有人可以指出错误。

1 个答案:

答案 0 :(得分:0)

问题是你从不提交表格,所以行动永远不会被执行。

这就是下载页面的样子:

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

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

相关问题