简体   繁体   English

使用PHP检查MySQL中是否存在值

[英]Check if a value exists in MySQL with php

I've been looking around stackoverflow and wasn't able to ever find a way that'd actually work. 我一直在寻找stackoverflow,却一直找不到真正可行的方法。 I have a simple php application 我有一个简单的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;
    }
}

Currently it seems to be hit or miss. 目前看来似乎很成功。 It'll work sometimes, other times a record will exist, and it'll still insert the userid again creating duplicates. 有时它将起作用,有时还会存在一条记录,并且仍然会再次插入用户ID以创建重复项。

phpmyadmin

Like said @tadman Your code is BAD. 就像@tadman所说的那样,您的代码是错误的。 Data from variable $json is directly inserted into query - this is not good... 来自变量$json数据直接插入查询中-这不好...

Simple test: 简单测试:

I set : 我设置 :

 $userid = "111111111a";

query: 查询:

 $sql = "SELECT * FROM log WHERE userid='111111111a' LIMIT 1";

return TRUE because, this user doesn't exists in db, 返回TRUE,因为该用户不存在于db中,

or 要么

 $userID ='111111111\' OR \'1=1';

query: 查询:

 $sql = "SELECT * FROM log WHERE userid='111111111' OR '1=1' LIMIT 1";

return TRUE because 1=1 is always true. 返回TRUE,因为1 = 1始终为true。

If column userid is INT type, $userid value is converted to 111111111 and inserted into log table 如果列userid为INT类型,则$ userid值将转换为111111111并插入到log表中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM