无法将sql查询输出保存为.csv格式

时间:2014-03-05 04:01:43

标签: php mysql

我遇到了sql查询的问题,有人帮助我。

在我的管理面板中,几乎没有下载数据的选项。 csv格式是通过使用数据库中的 sql查询来实现的。所有查询都是单个查询,并且可以在 Sql查询之后成功地<。>格式下以.csv格式下载数据。我无法下载此查询结果as.csv格式。

这就是为什么我问这个问题,我如何将这个查询输出(有2个while语句和长查询)保存为.csv格式?现在它不会将结果保存为.csv格式。

单一查询,例如

$sql = mysql_query("select * from user_property upr,  offers ofr where ofr.property_id 
= upr.property_id  and ofr.agent_id IN (select id from users where company_name !='') order 
by accept_ind asc");

Sql Query:

<?php
// Database Connection
$host="host";
$uname="username";
$pass="password";
$database = "database"; 
$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>");

$output = "`";

$q =  mysql_query("SELECT * FROM users WHERE company_name != '' ");
while($r= mysql_fetch_array($q)){

    $user_id = $r['id'];    
    $pc1 = $r['pc1'];
    $pc2 = $r['pc2'];
    $pc3 = $r['pc3'];
    $pc4 = $r['pc4'];                      
    $emailAgent = $r['user_email'];       

$sql =  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");

while($rrr =  mysql_fetch_array($sql)){ 

    $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;


    }// second while    
}/// first while...
?>

0 个答案:

没有答案