2011-12-01 136 views
0

我有一個CSV導出腳本,它從某個表格及其值中獲取某些字段並創建一個包含該數據的Excel文件。見下面的腳本。更改CSV導出的數據庫值

它首先獲取列名(ID除外)。 其次,它將獲取名字,姓氏,employee_id,單位和存在的值,並將所有這些值放入Excel文件中。

現在請注意,它從表中獲取數據:table_info 在此表中,UNIT和PRESENT僅存在於數字之外。這些數字代表單元的ID的/存在於來自其他兩個表:

table_units(ID,標題) table_presents(ID,標題)

我想有是,在Excel工作表沒有關係不顯示單位/目前的數字(編號),但顯示單位/目前的名稱。我怎樣才能做到這一點?我的PHP知識就在這裏停止。

 $table = 'table_info'; 
    $file = 'export'; 

    $result = mysql_query("SHOW COLUMNS FROM ".$table.""); 
    $i = 0; 
    if (mysql_num_rows($result) > 0) { 
     while ($row = mysql_fetch_assoc($result)) { 
      if($row['Field'] != 'id'){ 
       $csv_output .= $row['Field']."; "; 
       $i++; 
      } 
     } 
    } 
    $csv_output .= "\n"; 

    $values = mysql_query("SELECT firstname, familyname, employee_id, unit, present FROM ".$table."") or die(mysql_error()); 
    while ($rowr = mysql_fetch_row($values)) { 

     for ($j=0;$j<$i;$j++) { 
      $csv_output .= $rowr[$j]."; "; 
     } 
     $csv_output .= "\n"; 
    } 

    $filename = $file."_".date("Y-m-d_H-i",time()); 
    header("Content-type: application/vnd.ms-excel"); 
    header("Content-disposition: csv" . date("Y-m-d") . ".csv"); 
    header("Content-disposition: filename=".$filename.".csv"); 
    print $csv_output; 
    exit; 

回答

0

更改您的sql查詢以執行包含table_units和table_presents的連接。或者,如果擔心連接會導致性能瓶頸,則可以將table_units和table_present存儲在ID爲keyed的數組中,您可以在擁有foriegn鍵(unit_id,present_id)時參考該數組。

0

不知道爲什麼你正在使用的;代替,

下面是我發現的問題: -

$result = mysql_query("SHOW COLUMNS FROM ".$table.""); 
==> 
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field!='id'"); 
// so, it would skip column id 

所有for ($i ...)是沒有必要的,你必須在每一個額外;行,
做一個內爆代替: -

$csv_output .= $row['Field']."; "; 
==> 
$csv_output .= implode(';', $row);