我一直在 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 创建重复项。
最佳答案
就像 @tadman 所说,你的代码很糟糕。变量 $json
中的数据直接插入到查询中 - 这不好......
简单测试:
我设置:
$userid = "111111111a";
查询:
$sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";
返回 TRUE,因为数据库中不存在该用户,
或
$userID ='111111111\' OR \'1=1';
查询:
$sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";
返回 TRUE,因为 1=1 始终为 true。
如果列userid
为INT类型,则$userid值转换为111111111并插入log
表
关于php - 使用 php 检查 MySQL 中是否存在某个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31279715/