我有以下代码片段,当我尝试上传条目相对较小(〜500)的CSV文件时,该代码片段可以正常工作。但是,当条目变大(我尝试使用20,000)时,会触发以下错误。
您的sql语法有错误,请检查与您的mysql服务器版本相对应的手册,以在'S FANCY-KNDY0046','1298','32321','QE4224','2'附近使用正确的语法)'在第1行
我的INSERT into
看起来像这样:(还没有真正想到要清理此处的输入,但是您的想法也将派上用场!)
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT into universe (`zone`, `area`, `sub`) values('$emapData[0]','$emapData[1]','$emapData[2]')";
$result = mysqli_query($conn, $sql);
if(!$result )
{
echo "ERROR:". mysqli_error($conn); // I included this to see the error message.
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
mysqli_close($conn);
}
如果我在这里做错了,请感谢有人可以指出我!谢谢。
答案 0 :(得分:1)
很简单,在用'
换行的字符串中有一个''
,因此该字符串过早被破坏并导致语法错误。
如果您使用参数化查询,这对查询不会有任何影响,并且可以保护自己免受SQL Injection Attack
if($_FILES["file"]["size"] > 0) {
$file = fopen($filename, "r");
// prepare the query once and reuse lots of times
// reduces load on the server as well as the database
// only has to compile and optimize the query once
$sql = "INSERT into universe (`zone`, `area`, `sub`)
VALUES(?,?,?)";
$stmt = $conn->prepare($sql);
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE) {
$stmt->bind_param('sss', $emapData[0], $emapData[1], $emapData[2]);
$result = $stmt->execute();
if(!$result ) {
echo "ERROR:". $conn->error; // I included this to see the error message.
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
}