当我点击提交而不输入任何数据时,它只是显示请求被接受,而不能显示错误


When I click the submit without entering any data, it just appears that the request was accepted, and can not show me the error

所以,我的代码中有一个错误。他没有告诉我错误在|| echo"error - don GIVE CREDITS";||当我点击提交而不输入任何数据时,它只是显示请求被接受,并且不能显示错误"error - don GIVE CREDITS"。**


<?php
    $username = "root"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "cadastro"; 
    $user = $_POST['username'];
    $credits = $_POST['credit_amount'];
        if(verificarUser($user) == True)
        {
            $dbh = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password);
            $sql = "UPDATE users username SET credits = '{$credits}' WHERE username = '{$user}'";
            $count = $dbh->exec($sql);
                echo "<br /><font color='green'>O pedido foi realizado com sucesso na conta <b>$user</b> com <b>$credits creditos</b>.</font>";
            $dbh = null;
            }
            else
            {
                echo "<font color='red'>ERROR - DONT GIVE CREDITS</font>";
            }
        function verificarUser($username)
        {
            //connect database
            $dbh = new PDO("mysql:host=localhost;dbname=cadastro", "root", "");
            $procurarUser = $dbh->prepare("SELECT * FROM users");
            //save results
            $procurarUser->execute();
            //search
            $checkUser = $procurarUser->fetchAll();
            $dbh = null; //close db
            if(count($checkUser) > 0)
            {
                return True;
            }
            else
            {
                return False;
            }
        }
?>

您的verificarUser()函数所做的唯一事情是从数据库中获取所有用户(无论$username变量如何),如果找到超过0个用户,则返回true

所以只要你的数据库中至少有一个用户,你的verificarUser()函数将返回true,你将永远不会看到你的错误消息。

你可能想要这样写:

$procurarUser = $dbh->prepare("SELECT * FROM users WHERE username = :username");
$procurarUser->execute(array(':username' => $username));
检查给定的$username是否存在于数据库中。

如果users表中至少有一个用户,那么verificarUser($username)似乎总是返回True。由于顶部的else子句与if(verificarUser($user) == True)绑定,因此它永远不会执行。