当前位置:首页 > 数据库 > SQlite

PHP SQLite PDO检查用户是否在表中?

我正在尝试创建一个脚本,该脚本检查提供的用户名是否在表“ users”中,但“ if”语句始终返回false.用户表只有一列“用户名”,列出了所有用户.我究竟做错了什么?

$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT username from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

if($stmt->rowCount() > 0)
{
    //in the table
}
else{
    //not in the table
}

整个脚本:

<?php
require_once 'mclogin.class.php';
$api = new MinecraftAPI();
$user = $_POST['user'];
$password = $_POST['pword'];
if($api->login($user, $password)){
print $user;
$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT username from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

if($stmt->rowCount() > 0)
{
    echo "You are whitelisted";
}
else{
    echo "You are not whitelisted";
}

}else{
echo "Bad login";
}
?>

发送信息的页面:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title></title>
    </head>
    <body>

      <form name="input" action="login.do.php" method="post">
Username: <input type="text" name="user">
Password: <input type="password" name="pword">
<input type="submit" value="Submit">
      </form>  
    </body>
</html>

解决方法:

注意:

PDOStatement::rowCount() returns the number of rows affected by the
last DELETE, INSERT, or UPDATE statement executed by the corresponding
PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was
a SELECT statement, some databases may return the number of rows
returned by that statement. However, this behaviour is not guaranteed
for all databases and should not be relied on for portable
applications.

您应该改用以下代码,而只需使用fetch()方法检查结果是否为空.

$dbh = new PDO("sqlite:db.sqlite");
$stmt = $dbh->prepare("SELECT 1 from users where username = :name");
$stmt->bindParam(":name", $user);
$stmt->execute();

// use fetch instead of rowCount
if ($stmt->fetch()) {
  // in the table
} else {
  // not in the table
}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!