我有一个登录数据库,其中包含用户名和密码以及一个输入用户名和密码类型的html文件 .
在我的 class 登录:
class login
{
protected $_username;
protected $_password;
public function __construct($username, $password) //$username and $password values will be from the $_POST['username and password'] when the user submits the username and password
{
$this->username = $username;
$this->password = md5($password);
}
public function login()
{
try {
$pdo = dbConnect::getConnection();
$smt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
$smt->bindParam(1, $this->username);
$smt->execute();
echo "<pre>";
print_r($smt->fetch(PDO::FETCH_OBJ)); //testing if $smt will return results..yes it returned
if($smt->fetch()) {
print_r($smt->fetch(PDO::FETCH_OBJ)); //doesn't return ??this is my question... all other arguments inside this if loop is not executed..
while($row = $smt->fetch(PDO::FETCH_OBJ)) {
echo "one";
if($row->password == $this->password) {
header("Location: admin.php");
}
else {
echo '<div class="alert alert-error alert-block"><button type="button" class="close" data-dismiss="alert">×</button><h4>Error!</h4>username and password do not match!</div>';
}
}
}
else {
echo '<div class="alert alert-error alert-block"><button type="button" class="close" data-dismiss="alert">×</button><h4>Error!</h4>Username does not exist!</div>';
}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
}
问题是在PDO中,它不会返回我在if($ smt-> fetch()之后请求的数据,用于知道查询是否返回结果..在获取之前,print_r返回数据...我无法继续我的代码,因为这...我对OOP和PDO的新内容,这就是为什么我不能处理这个不同于mysql或mysqli函数..我是PDO新手,也是我在这里使用sqlite ..
1 回答
您正在多次获取:
这些行中的每一行都将尝试从返回的数据中获取下一行 . 但是您的查询看起来只返回一行 . 此行将由第一个
print_r()
打印 . 然后当您在if()
中再次获取时,将不会有任何内容,因此它将返回false
并且if
将失败 .您可以使用
$smt->fetchAll()
返回数组中的所有结果 . 然后,您可以测试此数组是否包含任何元素,并循环显示该数组以打印结果 .虽然我不明白你为什么使用循环,但你可以非常肯定查询永远不会返回超过1行 . 我总是看到这个,我不明白,除非程序员只是从其他返回多行的查询中复制代码,并且他们不理解循环是不必要的 .