gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:05:11 24 4
gpt4 key购买 nike

我正在尝试创建一个脚本来检查提供的用户名是否在表“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
}

关于PHP SQLite PDO 检查用户是否在表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12720648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com