在mysql中,我有一个包含列的表:
ID: INT(11) AUTO INCREMENT
keyowner: VARCHAR(255)
key: VARCHAR(5)
在php中,我有以下代码:
<?php
function get_client_ip() {
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$username = "root";
$host = "localhost";
$pass = "pass";
$db = "api";
$owner = get_client_ip();
$key1 = file_get_contents("afile");
$conn = new mysqli($host, $username, $pass, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "INSERT INTO api
(key_owner, key)
VALUES
($owner, $key1)";
if ($conn->query($query) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->error;
}
$conn->close();
?>
运行代码时,会显示错误:
错误:INSERT INTO api(key_owner,key)VALUES(an_ip,OF580) 您的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以便使用接近&#39;密钥的正确语法)VALUES(an_ip,afile)&#39;在第2行
答案 0 :(得分:1)
问题是密钥是SQL保留字。因此,要将其用作列/表名,请使用反引号(`)
还要为值添加引号。请检查以下代码。
$query = "INSERT INTO `api`
(`key_owner`, `key`)
VALUES
('$owner', '$key1')";
答案 1 :(得分:1)
AS keyowner: varchar(255) key: varchar(5
)。您需要在值周围添加quotes
来插入数据,key
是reserver keyword在mysql中,它必须位于backtick
。< / p>
要防止sql注入,请在插入数据库之前使用mysqli_real_escape_string
$key1 = mysqli_real_escape_string($conn,$key1 );
$owner = mysqli_real_escape_string($conn, $owner);
$query = "INSERT INTO api
(`key_owner`, `key`)
VALUES
('".$owner."', '".$key1."')";
<强>更新强>
因为您的表名是keys
。 keys
也是保留关键字,因此您需要围绕它进行反引号,以便最终查询
$key1 = mysqli_real_escape_string($conn,$key1 );
$owner = mysqli_real_escape_string($conn, $owner);
$query = "INSERT INTO `keys`
(`key_owner`, `key`)
VALUES
('".$owner."', '".$key1."')";
答案 2 :(得分:1)
可能你的价值观应该有引号,如下所示:
$query = "INSERT INTO `api`
(`key_owner`, `key`)
VALUES
('$owner', '$key1')";
我的建议是使用PHP PDO php.net