我有一个问题:
INSERT INTO tx3_hu_villages (uid,vid,x,y,name,population) VALUES
(122,2569,-29,36,'qwertzuiop',330),
(122,52915,-134,25,'asdfghjkléá',916)
ON DUPLICATE KEY UPDATE
name=VALUES(name),population=VALUES(population);
它在MySQL Workbench中工作正常,但在PHP中我收到此错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
CREATE TABLE `tx3_hu_villages` (
`vid` int(11) unsigned NOT NULL,
`uid` int(11) unsigned DEFAULT NULL,
`x` smallint(6) DEFAULT NULL,
`y` smallint(6) DEFAULT NULL,
`name` varchar(60) DEFAULT NULL,
`population` smallint(5) unsigned DEFAULT 0,
PRIMARY KEY (`vid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
没有ON DUPLICATE KEY UPDATE
也能正常使用PHP。
这是PHP代码:
$sql = "INSERT INTO ".$table_name."_villages (uid,vid,x,y,name,population) VALUES ";
for($i=0;$i<count($v);$i++){
$sql.= "(".$v[$i]['uid'].",".$v[$i]['vid'].",".$v[$i]['x'].",".$v[$i]['y'].",'".$v[$i]['village']."',".$v[$i]['population']."),";
}
$sql[strlen($sql)-1] = "";
$sql.= "ON DUPLICATE KEY UPDATE name=VALUES(name),population=VALUES(population);";
echo $sql;
有什么问题?
答案 0 :(得分:0)
执行这些多种插入的一种方法是使用像这样的PHP内爆函数
$sql = "INSERT INTO ".$table_name."_villages (uid,vid,x,y,name,population) VALUES ";
for($i=0;$i<count($v);$i++){
$temp[] = "(".$v[$i]['uid'].",".$v[$i]['vid'].",".$v[$i]['x'].",".$v[$i]['y'].",'".$v[$i]['village']."',".$v[$i]['population'].")";
}
$sql .= implode(',', $temp);
$sql.= " ON DUPLICATE KEY UPDATE name=VALUES(name),population=VALUES(population);";
echo $sql;
可能会避免与白空间相关的问题。