无法将数据库下载为CSV

时间:2018-08-12 16:39:26

标签: php mysql database select-into-outfile

我正在尝试下载整个数据库,但我不断收到错误消息:

  

解析错误:语法错误,意外的” LINES TERMINATED BY”   (T_CONSTANT_ENCAPSED_STRING)在C:\ wamp64 \ www \ cookies \ download_db.php中   在第6行

我的代码:

<?php 
    require 'db_key.php';

    $conn = mysqli_connect($servername, $username, $password, $dbname);

    $sql_query = mysqli_query($conn, "SELECT * FROM ventas INTO OUTFILE '/tmp/db_downlaod.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'");

    mysqli_query($conn, $sql) or exit(mysqli_error($conn));

    mysqli_close($conn);

    header('Content-type: text/csv');
    header('Content-disposition: attachment; filename=db_downlaod.csv');
    readfile('/tmp/db_downlaod.csv');
    unlink('/tmp/db_downlaod.csv');
    exit();
?>

非常感谢您提供任何帮助

1 个答案:

答案 0 :(得分:0)

您在enclosed by位关闭PHP SQL字符串,然后在下一个单引号处开始一个新字符串。您还需要对新行进行两次转义,因为您使用双引号,并且希望mysql将其获取为\n。试试:

$sql_query = mysqli_query($conn, "SELECT * FROM ventas INTO OUTFILE '/tmp/db_downlaod.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n'");

视觉:

$sql_query = mysqli_query($conn, "SELECT * FROM ventas INTO OUTFILE '/tmp/db_downlaod.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n'");
                                                                                                                                 closes PHP>^^<starts a new single quoted PHP string

您还要进行2个查询,第二个查询是针对未分配的变量$sql

删除:

mysqli_query($conn, $sql) or exit(mysqli_error($conn));

,或者有可能将该错误报告添加到第一个函数调用/查询执行中。