3

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

$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>
4

2 回答 2

4

笔记:

PDOStatement::rowCount() 返回受相应 PDOStatement 对象执行的最后一个DELETE、INSERT 或 UPDATE语句影响的行数。

如果关联 PDOStatement 执行的最后一条 SQL 语句是 SELECT 语句,则某些数据库可能会返回该语句返回的行数。但是,不能保证所有数据库都具有此行为 ,并且不应依赖于可移植 应用程序。

您应该改用下面的方法,只需使用该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
}
于 2012-10-04T06:05:17.547 回答
0

将第 2 行更改为

$stmt = $dbh->prepare("SELECT username from users where username = :name");

它会起作用。在 PDO 中使用参数背后的整个想法是,如果需要,它们会以 SQL 注入安全的方式自动引用。

出于您的目的,我通常使用:

$stmt = $dbh->prepare("SELECT COUNT(*) from users where username = :name");

这将返回一个结果,我总是可以直接在 if 之后直接使用,因为如果用户存在,它将返回一个,如果不存在则返回 0,或者在数据库错误时返回 false。

于 2012-10-04T05:52:06.570 回答