2011-08-12 61 views
3

解決的位置: 我只是需要改變這一行製作的Excel與PHPExcel文件,每列寫兩次

while ($row = mysql_fetch_array($result)) { 

while ($row = mysql_fetch_row($result)) { 


我使用PHPExcel拉來自mySQL數據庫的數據創建XLS文件。我正在寫兩欄:TITLE和VIEWS。 (標題是數據庫表中的實際列,視圖是每個標題在表中出現的次數)。

的數據寫入到XLS文件,問題是,每一列寫了兩次:

| ------- A ------- | -------乙------- | ------- -------ç| ------- ------- d |
5 --- TITLE --- | --- VIEWS --- |
6 ---標題1 --- | ----標題1 ---- | ------- 3 -------- | ------- 3-- ----- |
7 ---標題2 --- | ----標題2 ---- | ------- 6 -------- | ------- 6-- ----- |
8 ---標題3 --- | ----標題3 ---- | ------- 4 -------- | ------- 4-- ----- |

我該如何解決這個問題,讓它顯示每個列一次?

我的代碼:

$sql = " 
    SELECT 
     titles.title, 
     COUNT(DISTINCT history.id) AS `count` 
    FROM 
     user_history titles 
    LEFT OUTER JOIN 
     user_history history 
    ON 
     titles.title = history.title 
    "; 


    $sql .= " 
    GROUP BY 
     titles.title 
    ORDER BY 
     titles.title 
    "; 

    $result = mysql_query($sql); 
$headings = array('Title', 'Views'); 

if ($result = mysql_query($sql) or die(mysql_error())) { 


    $rowNumber = 5; 
    $col = 'A'; 
    foreach($headings as $heading) { 
     $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading); 
     $col++; 
    } 

    // Loop through the result set 
    $rowNumber = 6; 
    while ($row = mysql_fetch_array($result)) { 
     $col = 'A'; 
     foreach($row as $cell) { 
      $objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell); 
      $col++; 
     } 
     $rowNumber++; 
    } 
+0

如果你不需要任何特殊的格式,你有沒有考慮只是寫一個CSV文件? –

+0

@SimpleCoder - 我確實需要特殊的格式。 – nitsuj

+0

關於如何爲pdo做到這一點的任何建議似乎總是做一個行取回呢? http://php.net/manual/en/pdostatement.fetch.php – pal4life

回答

0

因爲你的加入是無損的。

你得到冗餘信息兩次

只是這樣做您的查詢:

SELECT 
    titles.title, 
    COUNT(DISTINCT titles.id) AS `count` 
FROM user_history titles 
GROUP BY titles.title 
ORDER BY titles.title; 
+0

這沒有什麼區別。 – nitsuj