Announcement

Collapse
No announcement yet.

Export table to CSV ....

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Export table to CSV ....

    Hi all,
    After googling I've copied this code into a button code of a control to generate a csv file starting from a myslq table
    I got added a text field where I insert a table name too.
    It don't give errors running but make a real mess on output...csv file.
    For me it's to difficult to understand where is the problem.
    Attached the CSV produced... better the something... produced.


    $table = '{table_name}' or $table = "eos_b2bc.orders_details";
    $filename = tempnam(sys_get_temp_dir(), "csv");

    $conn = mysql_connect("localhost", "root", "");
    mysql_select_db("eos_b2bc",$conn);

    $file = fopen($filename,"w");

    // Write column names
    $result = mysql_query("show columns from $table",$conn);
    for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $colArray[$i] = mysql_fetch_assoc($result);
    $fieldArray[$i] = $colArray[$i]['Field'];
    }
    fputcsv($file,$fieldArray);

    // Write data rows
    $result = mysql_query("select * from $table",$conn);
    for ($i = 0; $i < mysql_num_rows($result); $i++) {
    $dataArray[$i] = mysql_fetch_assoc($result);
    }
    foreach ($dataArray as $line) {
    fputcsv($file,$line);
    }

    fclose($file);

    header("Content-Type: application/csv");
    header("Content-Disposition: attachment;Filename=output_file.csv");

    // send file to browser
    readfile($filename);
    unlink($filename);
    Attached Files
Working...
X