因此,我试图创建一个表,然后将多个值插入该表,如下所示:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "someDbName";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "CREATE TABLE IF NOT EXISTS someTableName(
someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
someVar1 VARCHAR(30) NOT NULL,
someVar2 INT NOT NULL);
INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ('someString1', someInteger1),
('someString2',someInteger2);";
其中someInteger位当然是整数。然后:
$sql = mysqli_real_escape_string($conn, $sql);
if (mysqli_multi_query($conn, $sql)) {
dtconsole("Tables populated successfully");
} else {
dtconsole("Error creating table: " . mysqli_error($conn));
}
使用dtconsole函数可以将其输出到控制台以帮助我进行调试。
function dtconsole($data){
$output=$data;
if(is_array($output)){
$output=implode(',',$output);
}
echo '<script>console.log("'.$output.'");</script>';
}
每次尝试运行此命令时,都会返回以下错误:
错误创建表:您的SQL语法有错误;检查 对应于您的MariaDB服务器版本的手册 在'附近使用的语法 someID INT(6)UNSIGNED AUTO_INCREMENT PRIMARY KEY,位于第1行
我一生都看不到我在做错什么。
答案 0 :(得分:1)
您的问题是您要在整个查询中调用mysqli_real_escape_string
,而不仅仅是插入的值。结果,它将$ sql字符串中的CR-LF转换为\r\n
,MySQL解析器无法解释。您应该这样做:
$someString1 = mysqli_real_escape_string($conn, 'someString1');
$someString2 = mysqli_real_escape_string($conn, 'someString2');
$sql = "CREATE TABLE IF NOT EXISTS someTableName(
someID INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
someVar1 VARCHAR(30) NOT NULL,
someVar2 INT NOT NULL);
INSERT INTO someTableName (someVar1 , someVar2 ) VALUES ($someString1, someInteger1),
($someString2,someInteger2);";
if (mysqli_multi_query($conn, $sql)) {
...