Mysql查询结果不是使用php将文件保存为csv格式

时间:2014-03-04 11:36:04

标签: php mysql

我正在尝试从mysql数据库中获取数据并使用php将其保存为.csv格式。但没有运气。它不会将查询输出保存为.csv格式。我的代码中是否有任何问题,或者有任何解决方案可以解决它。

感谢您的帮助。

<?php
// Database Connection
$host="host..";
$uname="username..";
$pass="password...";
$database = "database...."; 

$sqlagentdetails = "select * from users WHERE company_name != ''";
$rowresult = mysql_query($sqlagentdetails); 
while($row = mysql_fetch_array($rowresult, MYSQL_ASSOC))
{
    $pc1 = $row['pc1'];
    $pc2 = $row['pc2'];
    $pc3 = $row['pc3'];
    $pc4 = $row['pc4'];                      
    $emailAgent = $row['user_email'];                      
    $user_id = $row['id'];


$myQuery =  mysql_query("
 SELECT * 
   FROM user_property upr 
  WHERE (postcode = '$pc1' OR
         postcode = '$pc2' OR
         postcode = '$pc3' OR
         postcode = '$pc4') AND
         datediff(CURDATE(), upr.creation_date) <= 7 AND
         NOT EXISTS(SELECT ofr.property_id 
                      FROM offers ofr 
                     WHERE ofr.property_id = upr.property_id AND
                           ofr.agent_id IN(SELECT id 
                                             FROM users 
                                            WHERE company_name !=''
                                          )
                   )
ORDER BY property_id DESC");


if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();

for ($i = 0; $i < $num_fields; $i++) {
    $headers[] = mysql_field_name($result , $i);
}

$fp = fopen('php://output', 'w');

if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, $headers);
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
    }
    die;
}

}// first while statement

?>

1 个答案:

答案 0 :(得分:0)

MYSQLI_NUM在这做什么?什么是$result?尝试:

 while ($row = mysql_fetch_assoc($myQuery)) {
    fputcsv($fp, array_values($row));
 }

你应该停止使用mysql_ *函数,因为它们已被弃用。查看PDOmysqli