如何使用PHP在单个CSV列中插入多个值?

时间:2012-03-06 11:29:50

标签: php mysql csv

我在使用php导出csv文件时遇到问题,一切都很好,除了产品,我希望所有产品都在一个单元格中,产品来自不同的表,我尝试使用以下代码,但无法获得结果,因为我期待, 请帮我。 感谢

ID    Status    Products        Buyer Name
1     Pending   book1, book2    bheem


$row = array();

$row[] = 'ID';

$row[] = 'Status';

$row[] = 'Products';

$row[] = 'Buyer Name';

$data .= join(',', $row)."\\n";

$query = sprintf( "SELECT * FROM orders WHERE order_id='{$_GET['order_id']}'" );
$result = mysql_query( $query ) or die( mysql_error() );
$row2 = mysql_fetch_assoc( $result ); 
$row = array(); // We must clear the previous values
$row[] = $row2['order_id'];     
$row[] = $row2['status'];

//Browse product name
$product_q = sprintf("SELECT * FROM books WHERE bid='{$row2['bid']}'");
$res_prd = mysql_query($product_q);
$prow = '';
while($prows = mysql_fetch_assoc($res_prd)) {   
    $prow.= $prows['product_name'];                     
}   
    $row[] = $prow; 

$row[] = $row2['buyer_name'];
$data .= join(',', $row)."\n";

header("Content-type: application/x-msdownload");

header("Content-Disposition: attachment; filename=order.csv");

header("Pragma: no-cache");

header("Expires: 0");

echo $data;

3 个答案:

答案 0 :(得分:0)

$query = sprintf( "SELECT * FROM orders WHERE order_id='{$_GET['order_id']}'" );
$result = mysql_query( $query ) or die( mysql_error() );
 $row2 = mysql_fetch_assoc( $result );
  while($row2 = mysql_fetch_assoc( $result )) {    

    $row = array(); // We must clear the previous values
    $row[] = $row2['order_id'];
    $row[] = $row2['status'];

    $product_q = sprintf("SELECT * FROM books WHERE bid='{$row2['bid']}'");
    $res_prd = mysql_query($product_q);
    $prow = '';
    while($prows = mysql_fetch_assoc($res_prd)) {   
          $prow.= $prows['product_name'];                       
        }   //End inner foreach 
    $row[] = $prow; //End while 
    $row[] = $row2['buyer_name'];

    $data .= join(',', $row)."\n";
  }

尝试这样......可能会有帮助:)

答案 1 :(得分:0)

使用连接确实使这些东西更容易。

$orderid = intval($_GET['order_id']);
$query = sprintf("SELECT order_id, status, product_name, buyer_name FROM books INNER JOIN orders ON bid = order_id WHERE order_id='{$orderid}'");

现在您的查询将得到一个包含以下内容的数组: order_id,status,product_name,buyer_name

破坏你的结果并输出内容和你的成就。

答案 2 :(得分:0)

问题在于','是单元格分隔符,并且当您列出产品时使用',',这会将每个产品推送到新单元格中。

我认为您需要做的就是将while循环更改为:

$prow = '';
while($prows = mysql_fetch_assoc($res_prd)) { 
    if($prow === '') {$prow = '"';}//start escaping the cell
    else{$prow .=', ';} // separate each product by a space and comma
    $prow.= $prows['product_name'];//add the product name
} 
$prow .= '"';//finish escaping the cell

通过将产品单元格用双引号括起来转义,可以在该单元格中使用逗号。

相关问题