我的代码:
for($i=0; $i<count($_POST['value']);$i=$i+3)
{
$sql = "(NULL, '".$_POST['value'][$i]."', '".$_POST['value'][$i+1]."', '".$_POST['value'][$i+2]."')";
}
$query = "INSERT INTO 'googlemaps'.'values' ('id','lat','long','desc') VALUES ".$sql;
但是我在 SQL 中得到了这个错误
#1064 - Erreur de syntaxe près de ''googlemaps'.'values'
('id','lat','long','desc') VALUES (NULL, '20.593684', '78.' Ã la
ligne 1
有人能指出这里出了什么问题吗?
或任何其他方式来简化此代码?
我猜你打算插入到 googlemaps 表中,而不是一个名为 googlemaps 的数据库和一个名为 values 的表(如果我弄错了,请告诉我,我会编辑我的答案)。所以这是第一件事。接下来是您要使用反引号而不是单引号表和列名称。
$query = "INSERT INTO `googlemaps` (`id`,`lat`,`long`,`desc`) VALUES ".$sql;
反引号是引号标识符,可以防止您在需要列名或表名时意外使用保留关键字。
The identifier quote character is the backtick (“`”) Click here to read more
因为除了 desc 和 long 之外你没有使用任何关键字,你也可以这样写你的查询:
$query = "INSERT INTO googlemaps (id,lat,`long`,`desc`) VALUES ".$sql;
因为没有人想要 SQL 注入(inject),您可以像这样修改您的 for 循环:
$sql = "(NULL, '".mysqli_escape_string($db, $_POST['value'][$i])."', '".mysqli_escape_string($db, $_POST['value'][$i+1])."', '".mysqli_escape_string($db, $_POST['value'][$i+2])."')";
mysqli_escape_string Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection. Read more by clicking here
看起来你也在尝试做一个扩展插入
您的最终代码看起来像这样(将 $db 设置为您的连接变量是什么):
$sql = []; // define as an array
for($i=0; $i<count($_POST['value']);$i=$i+3) {
$sql[] = "(NULL, '".mysqli_escape_string($db, $_POST['value'][$i])."', '".mysqli_escape_string($db, $_POST['value'][$i+1])."', '".mysqli_escape_string($db, $_POST['value'][$i+2])."')";
}
$query = "INSERT INTO googlemaps (id,lat,`long`,`desc`) VALUES ".implode(',', $sql);
Iplode 会将 SQL 字符串重新连接在一起,以逗号分隔
implode Join array elements with a string Read more by reading the documentation here