PHP函数似乎有问题

时间:2017-01-04 08:21:20

标签: php mysql function pdo return

此代码中的某些内容无法正常工作。需要你的帮助。

我在外部文件中编写了一个函数:

function userExists($conn, $user){
    $sql = "SELECT COUNT(*) FROM user WHERE email = :email";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':email', $user);
    $stmt->execute();
    $results = $stmt->fetch(PDO::FETCH_ASSOC);
    if(count($results) > 0):
        return true;
    else:
        return false;
    endif;
}

我在这里称这个功能:

if(!empty($_POST['email']) && !empty($_POST['password'])):
    $email = $_POST['email'];
    $password = $_POST['password'];

    $records = $conn->prepare('SELECT id,username,email,password,active FROM user WHERE email = :email');
    $records->bindParam(':email', $_POST['email']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);
    if(userExists($conn, $email) === false){
         echo 'False';
    }else{
         echo 'True';
    }
endif;

但每次输出都是真的..也许我看不到树木的木材。

THX

1 个答案:

答案 0 :(得分:1)

结果将始终大于0,因为您的查询返回值0.因此结果确实包含值。而是这样做

"SELECT COUNT(*) AS Total FROM user WHERE email = :email";"
if($result['Total'] > 0)
{.....}