3

指定されたユーザー名がテーブル「users」にあるかどうかをチェックするスクリプトを作成しようとしていますが、「if」ステートメントは常にfalseを返します。usersテーブルには、すべてのユーザーを一覧表示する「username」列が1つだけあります。私は何が間違っているのですか?

$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");

これは、ユーザーが存在する場合は1、存在しない場合は0、データベースエラーの場合はfalseを返すため、直後のifで常に直接使用できる結果を返します。

于 2012-10-04T05:52:06.570 に答える