使用PHP从两个表中将MYSQL导出到.csv

时间:2016-05-31 17:11:10

标签: php mysql csv

我有2张门票回复

门票获得此字段: ID,dname,mname,subject,priority,message,date,last_reply,status,close_mname,cdfileds

回复得到此文件: id,tid,mname,message,date

这些表是支持票。 我想将表导出为CSV。 这是我使用的代码。

<?php
/* vars for export */
// database record to be exported
$db_record = 'trxp_tickets';
$db_record2 = 'trxp_replies'; // added by me
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';
// database variables
$hostname = "localhost";
$user = "xxxxx";
$password = "xxxxx";
$database = "xxxxxx";
// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
    or die('Could not connect: ' . mysql_error());

mysql_select_db($database)
    or die ('Could not select database ' . mysql_error());
// create empty variable to be filled with export data
$csv_export = '';
// query to get data from database
$query = mysql_query("SELECT id,dname,mname,subject,priority,message,date,last_reply,status,close_mname,cdfields FROM ".$db_record." ".$where);
$field = mysql_num_fields($query);
// create line with field names
for($i = 0; $i < $field; $i++) {
    $csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';
// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
    // create line with field values
    for($i = 0; $i < $field; $i++) {
        $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
    }   
    $csv_export.= '
';  
}
// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>

在代码中,当我进行SELEC时,它不包含在第二个表中,对于双打结果。尝试使用UNION和UNION ALL但不起作用。 我想留在下面列出的每张票证回复中的CSV。

1 个答案:

答案 0 :(得分:0)

更改SQL以从两个表中获取数据:

$query = mysql_query("SELECT 
                          r1.id, r1.dname, r1.mname, r1.subject,
                          r1.priority, r1.message,
                          DATE_FORMAT(FROM_UNIXTIME(r1.date), '%d/%m/%Y') as r1_date,
                          r1.last_reply, r1.status, r1.close_mname,
                          r1.cdfields,
                          r2.id, r2.tid, r2.mname,
                          r2.message
                          DATE_FORMAT(FROM_UNIXTIME(r2.date), '%d/%m/%Y') as r2_date,
                     FROM ".$db_record." r1
               INNER JOIN ".$db_record2." r2 
                       ON r1.id = r2.tid
                          ".$where.");

这应该可以解决问题。

不推荐使用

mysql_ *函数。您应该更改为mysqli_ *或PDO。 (http://php.net/manual/en/function.mysql-query.php