我一直在寻找stackoverflow,并且无法找到实际工作的方式。我有一个简单的PHP应用程序
//Database credentials
$servername = "localhost";
$username = "root";
$password = "password";
$database = "database";
// Create connection to database
$db = new mysqli($servername, $username, $password, $database);
// Check connection for errors
if ($db->connect_error) {
die("<h1>Connection to database failed: " . $db->connect_error) . "</h1>";
};
$username = $json['statuses'][0]['user']['screen_name'];
$userid = $json['statuses'][0]['user']['id_str'];
$sql = "SELECT * FROM log WHERE userid='" . $userid . "' LIMIT 1";
if ($db->query($sql)->num_rows > 0) {
echo "<h4>This user already exists</h4>";
} else {
//Put the userid into the database
$sql = "INSERT INTO log (userid) VALUES ('" . $userid . "')";
if ($db->query($sql) === TRUE) {
echo "<h4>Added " . $username . " to the database</h4>";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
}
目前它似乎被击中或错过了。它有时会工作,有时会存在记录,并且它仍然会再次插入用户ID以创建重复项。
答案 0 :(得分:1)
就像说@tadman你的代码很糟糕。变量$json
中的数据直接插入到查询中 - 这不太好......
简单测试:
我设置:
$userid = "111111111a";
查询:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
返回TRUE,因为此用户不存在于db,
中或
$userID ='111111111\' OR \'1=1';
查询:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
返回TRUE,因为1 = 1始终为真。
如果列userid
是INT类型,$ userid值将转换为111111111并插入log
表