如何在PHP中的mysqli_query()中转义双引号字符?

时间:2014-09-16 09:44:24

标签: php mysql sql csv phpmyadmin

我正在尝试使用CSV文件更新mysql数据库。

我在phpmyadmin中使用此查询

LOAD DATA INFILE 'C:/wamp/www/website/test_mysql_import.csv' INTO TABLE `csv_preset` FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\n'    

但是当我尝试在mysqli_query函数中使用它时,它不会更新数据库。

这里是完整的代码块:

<?php require "db_connect.php"; ?>    
    <?php
    $csv_file = "C:/wamp/www/website/test_mysql_import.csv";

    $sql_dump ="TRUNCATE TABLE csv_preset";
    $sql_update = "LOAD DATA INFILE '$csv_file' INTO TABLE `csv_preset` FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\n'");
    mysqli_query($db_conx, $sql_dump);
    mysqli_query($db_conx, $sql_update);
?>    

2 个答案:

答案 0 :(得分:1)

<?php require "db_connect.php"; ?>    
    <?php
    $csv_file = "C:/wamp/www/website/test_mysql_import.csv";

    $sql_dump ="TRUNCATE TABLE csv_preset";
    $sql_update = "LOAD DATA INFILE '".$csv_file."' INTO TABLE `csv_preset` FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\"' LINES TERMINATED BY '\n'");
    mysqli_query($db_conx, $sql_dump);
    mysqli_query($db_conx, $sql_update);
?> 

答案 1 :(得分:0)

请尝试使用此代码:

        $sql_update = "LOAD DATA INFILE $csv_file INTO TABLE `csv_preset` FIELDS TERMINATED BY ',' ENCLOSED BY &quot; ESCAPED BY &quot; LINES TERMINATED BY \\n";

您的变量不需要单引号,因为它已经是双引号。双引号可以使用htmlcode和带有“\”的换行来转义它们。