2012-03-05 4 views
0

PHP를 처음 사용했습니다. PHP를 사용하여 MySQL 데이터베이스에서 Excel 시트를 생성하려면 다음 코드를 사용하고 있습니다.PHP를 사용하여 MySql 데이터베이스에서 엑셀 시트 생성하기

<?php 
    include("../Connection/Connection.php"); 
    $db_con=new Connection(); 
    $db_con->get_connection(); //Opens a database connection. This function is contained in the Connection.php which is included above. 

    $result = mysql_query("SELECT * FROM country"); 
    if (!$result) die('Couldn\'t fetch records'); 
    $num_fields = mysql_num_fields($result); 
    $headers = array(); 

    for ($i = 0; $i < $num_fields; $i++) 
    { 
     $headers[] = mysql_field_name($result , $i); 
    } 

    $fp = fopen('php://output', 'w'); 
    if ($fp && $result) 
    { 
      header('Content-Type: text/csv'); 
      header('Content-Disposition: attachment; filename="export.csv"'); 
      header('Pragma: no-cache'); 
      header('Expires: 0'); 
      fputcsv($fp, $headers); 

      while ($row = mysql_fetch_array($result)) 
      { 
       fputcsv($fp, array_values($row)); 
      } 
      die; 
    } 
?> 

상기 코드는 작동하고 지정된 파일을 생성 export.csv 그러나 문제는 두 파일이 MySQL은 각 열을 발생한다는 것이다. 즉, 각 열은 두 번 중복됩니다 (표시된 헤더는 중복되지 않습니다). 이 코드의 문제점은 무엇입니까? 각 열을 정확히 한 번 표시하도록 변경해야하는 항목은 무엇입니까?

답변

2

대신 mysql_fetch_row을 사용하십시오.

mysql_fetch_array은 두 문자열 인덱스와 숫자 인덱스를 사용하여 배열을 반입하므로 각 값이 두 번 반입됩니다. 코드는 mysql_fetch_assoc 또는 mysql_fetch_row으로 작동합니다.

+0

나는 당신이 말한대로했고 예상대로 작동했습니다. 시간 내 줘서 고마워. – Bhavesh

관련 문제