我有一个愚蠢的问题。我正在尝试将批量数据从csv文件上传到我的数据库表。它工作正常。但是我注意到csv文件中的许多行都包含单引号词中的数据,如(那' s,It' s等)。数据库单引号中的任何位置查询都会引发语法错误。我看到很多帖子建议你保留单引号数据(那'' s),但我有超过1000行,所以我无法检查每一行。有什么编程方法可以避免这个问题吗?
<?php
include "connection.php"; //Connect to Database
$deleterecords = "TRUNCATE TABLE tablename"; //empty the table of its current records
mysql_query($deleterecords);
//Upload File
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
echo "<h2>Displaying contents:</h2>";
readfile($_FILES['filename']['tmp_name']);
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$import="";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
print ""
//view upload form
}else {
print "<h1>Upload new CSV</h1><br />\n";
print "<form enctype='multipart/form-data' action='upload.php' method='post'>";
print "File name to import:<br />\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Upload'></form>";
}
?>
答案 0 :(得分:1)
首先,你需要停止使用mysql_*
函数,因为它在php 7.0上被省略而是使用mysqli_*
或PDO
您可以使用addslashes()
添加反斜杠以转义单引号和双引号,或者由于您要插入数据库,因此需要使用mysql_real_escape_string()
mysql_real_escape_string($import);