Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法检查数据库PHP中是否存在用户_Php_Sql - Fatal编程技术网

无法检查数据库PHP中是否存在用户

无法检查数据库PHP中是否存在用户,php,sql,Php,Sql,我遇到一种情况,我必须检查数据库中是否存在用户,我尝试以下方法: $username = htmlspecialchars($_POST['userName']); /* Check if username is free*/ if(!isset($error_message)) { if(!isset($_POST["userName"])) { $error_message = " All Fields are required"; } else { $db_handle = new

我遇到一种情况,我必须检查数据库中是否存在用户,我尝试以下方法:

$username = htmlspecialchars($_POST['userName']);
/* Check if username is free*/
if(!isset($error_message)) {
if(!isset($_POST["userName"])) {
$error_message = " All Fields are required";
} else {
    $db_handle = new mysqli("localhost", "root", "pass", "database");
    $query = 'SELECT * FROM naudotojai WHERE username = "$username"';
    $result = $db_handle->query($query);
    if($result->num_rows == 0) {
        $error_message = "Do not exist";
}
}
}
但它不起作用。即使输入数据库中存在的有效用户名,它也始终返回0行

mysqli_result Object ( [current_field] => 0 [field_count] => 7 [lengths] => [num_rows] => 0 [type] => 0 ) 
然后我有第二个脚本,在这里我检查用户名是否是免费的,这很好:

 $username = htmlspecialchars($_POST['userName']);
    /* Check ir username is free*/
    if(!isset($error_message)) {
    if(!isset($_POST["userName"])) {
    $error_message = " All Fields are required";
    } else {
        $db_handle = new mysqli("localhost", "root", "pass", "database");
        $query = 'SELECT * FROM naudotojai where username = "$username"';
        $result = $db_handle->query($query);
        if(!empty($result)) {
            $error_message = "Exists";
    }
    }
    }
你能帮我解决这个问题吗?我自己想不出来

编辑:当我手动输入用户名时,它工作正常。因此,问题在于查询中的变量。但我不明白。为什么它对一个查询有效,而对另一个查询无效

$query = 'SELECT * FROM naudotojai WHERE username = admin';

您使用的是单引号字符串来构建查询,因此不会替换字符串$username

尝试使用

"SELECT * FROM naudotojai where username = '$username'"

但是更好的方法是使用一个准备好的语句来避免SQL注入。

您可以将PDO与PHP结合使用

}else{
    $dbh = new PDO('mysql:host=localhost;dbname=database', "root", "pass");
    $sth = $dbh->prepare("SELECT * FROM naudotojai where username = :username");
    $sth->execute(":username" => $username);
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);

    if($result){
       // do something
   }

}

因此,在查询中,您有变量$username,但在哪里设置?因为在此之前,您正在检查变量$\u POST['userName'],该变量不相同。请编辑它,抱歉。您的代码容易受到SQL注入的攻击。请学习使用。好的,接下来,您知道php中单引号和双引号的区别吗?另外,如果您只需要检查用户,我建议您从naudotojai中选择1,其中username=:usernameYes,它起作用了。但是在我的第二个例子中,为什么变量被替换了,并且工作得很好呢?第二个例子也是如此。只是因为你的逻辑颠倒了。我很确定,只有当您尝试创建用户名等于$username的用户时,才会收到错误消息。