繁体   English   中英

如何将查询结果导出到csv文件?

[英]How to export query result to csv file?

是否可以由此创建 csv 文件?

数据库中的这张表看起来像下面的一个回声

 id | category| supplier | price 1 | A | supplier1 | 5 2 | B | supplier2 | 3 3 | B | supplier1 | 7 4 | C | supplier3 | 6 5 | C | supplier1 | 2 6 | B | supplier3 | 9
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";

$con = mysql_connect($host,$user,$pass);
if($con)
{
      $db = mysql_select_db('stocks');
       if($db)
       {}
       else 
       {
         echo "No Database Found! " ;
        }
}
else 
{
     echo "Failed to Connect! ";
}
?>
<table>
<tr>
    <th>Category</th>
    <th>Stock</th>
    <th>Percentage</th>
</tr>
<?php
$total=6;
        $q="SELECT id,name,supplier,price,COUNT(*) FROM  items GROUP BY supplier";
        $r = mysql_query($q);
        while($row = mysql_fetch_array($r))
        {
                 $ratio=($row['COUNT(*)']/$total)*(100);
            echo "<tr>";
echo "<td>" . $row['category'] . "</td>";
echo "<td>" . $row['COUNT(*)'] . "</td>";
echo "<td>" . round($ratio,2). "%</td>";
echo "</tr>";
        }
echo "</table>";        
         ?>

我怎样才能把它放在 csv 中?

我只知道这样做是为了选择表中的所有内容。

类别库存百分比 A 1 16.67% B 3 50% C 2 33.33%

您可以为此使用 php 函数 fputcsv。 我正在分享一个示例工作代码。

$output = fopen('result.csv', 'w');

$rs=mysql_query($sql,$conn);

while($row = mysql_fetch_assoc($rs)) {
    fputcsv($output, $row);
}
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

链接到页面http://code.stephenmorley.org/php/creating-downloadable-csv-files/希望适合您的需求

while($row = mysql_fetch_array($r))
        {   $data=array($row['category'],$row['COUNT(*)'],round(($row['COUNT(*)']/$total)*(100),2));
            fputcsv($output, $data);
        }

@Davinder @Virgilio 这确实有效,但在 C:\\xampp\\htdocs\\revamp\\csv.php 中第 39 行出现错误消息(解析错误:语法错误,意外的 ')'),但它完美地工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM