无法从MySQL表创建CSV文件

时间:2017-10-26 06:01:10

标签: php mysqli

结果将失败。我无法导入CSV文件。查询中有什么问题?

<?php
$conn = mysqli_connect("localhost","root","","excelupload");
$enclose = '"';
$slash = '\n';
$select = "SELECT *
FROM diamond_data
INTO OUTFILE 'excelupload/table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '".$enclose."'
LINES TERMINATED BY '".$slash."'";

$result = mysqli_query($conn,$select);
if($result){
    echo "success";
}
else{
    echo "fail";    
}
?>

1 个答案:

答案 0 :(得分:0)

<?php
   ini_set('memory_limit', '256M');
   $filename = 'table.csv';
   $conn = mysqli_connect("localhost","root","","test");
// Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql_query = "SELECT * FROM user_details";

    // Gets the data from the database
    $result = $conn->query($sql_query);
    $f = fopen('php://temp', 'wt');
    $first = true;
    while ($row = $result->fetch_assoc()) {

        if ($first) {
            fputcsv($f, array_keys($row));
           $first = false;
        }
        fputcsv($f, $row);
    } // end while

    $conn->close();

    $size = ftell($f);
    rewind($f);

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Length: $size");
    // Output to browser with appropriate mime type, you choose ;)
    header("Content-type: text/x-csv");
    header("Content-type: text/csv");
    header("Content-type: application/csv");
    header("Content-Disposition: attachment; filename='".$filename."'");
    fpassthru($f);
    exit;

?>
相关问题