简体   繁体   中英

PHP EXPORT MYSQL TO CSV - got column headers, can't get rest of data?

I can't seem to figure out why my table data won't appear in the csv file. I have 1 page with a form submit to start the export process. I am getting the correct column headers when I open the file with excel...

Thanks for the help!!

if(isset ($_POST['submit'])) {
        $host = "";
        $user = "";
        $password = "";
        $db = "";
        $con = mysql_connect("$host", "$user", "$password") or die("Couldn't connect to server.");  
        $db = mysql_select_db("$db", $con) or die ("Couldn't select database.");
        $table = "wp_users";

    function exportMysqlToCsv($table,$filename = 'content.csv') {

    $csv_terminated = "\n";

    $csv_separator = ",";

    $csv_enclosed = '"';

    $csv_escaped = "\\";

    $query = "select * from $table";

    $result = mysql_query($query);

    $rowcount = mysql_num_fields($result);

    $data = '';

    for ($i = 0; $i < $rowcount; $i++) {

    $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,

    mysql_field_name($result, $i)) . $csv_enclosed;

    $data .= $l;

    $data .= $csv_separator; }

    $output = trim(substr($data, 0, -1));

    $output .= $csv_terminated;

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

    $data = '';

    for ($j = 0; $j < $fields_cnt; $j++) {

    if ($row[$j] == '0' || $row[$j] != '') {

    if ($csv_enclosed == '') { $data .= $row[$j]; }

    else { $data .= $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed; } }

    else { $data .= ''; }

    if ($j < $rowcount - 1) { $data .= $csv_separator; } }

    $output .= $schema_insert;

    $output .= $csv_terminated; }

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header("Content-Length: " . strlen($output));

    header("Content-type: text/x-csv");

    //header("Content-type: text/csv");

    //header("Content-type: application/csv");

    header("Content-Disposition: attachment; filename=$filename");

    echo $output;

    exit;

    } 

    exportMysqlToCsv($table);

    }

The problem appears to be that you are assigning the CSV string to the $data variable but you are not appending it to $output . You need a line like:

$output .= $data;

just before:

$output .= $csv_terminated;

Secondly, I really recommend you to fix the code structure. It is very difficult to read the code the way it is right now. Read PSR standards for more information (or there are tons of decent standards).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM