我从网上得到了一个 pdo 类。现在,当我想在 auth 类中使用它时,我收到了任何结果。下面我放了我的pdo的一些函数。
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
//binds the inputs with the placeholders we put in place
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
//$this->stmt->bindValue($param, $value, $type);
$this->stmt->bindParam($param, $value, $type);
}
//executes the prepared statement
public function execute(){
return $this->stmt->execute();
}
// returns an array of the result set rows
public function resultset(){
$this->stmt->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
// returns a single record from the database
public function resultRow(){
$this->stmt->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
然后这是我如何在我的 auth 类的登录函数中使用它。
public function login($user, $password){
//$pdo is a new of database class!
$pdo->query("SELECT user,pass FROM users WHERE user = ':user' , pass = ':pass'");
$pdo->bind(':user', $user);
$pdo->bind(':pass', $password);
$result = $pdo->resultRow();
if($result == true) { //do sth
return true;
}
else return false;
}
它返回 false!由于这是我第一次在 php 项目中使用 pdo,所以我对它的使用有点困惑。
出了什么问题?
最佳答案
无需在占位符周围使用 ''
。这就是占位符的全部意义。删除 :user
和 :pass
周围的 ''
。您提供的 SQL 无效(除此之外,您还使用 ,
而不是 AND
来连接 WHERE
语句的两个部分) .
您还可以通过将 PDO::ATTR_ERRMODE
设置为 PDO::ERRMODE_EXCEPTION
将 PDO 置于更合适的 Debug模式。这使得调试任何 SQL 问题变得更加容易。
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
此外,我想评论一下,在 PDO 类中使用“当前”语句并不是一个非常灵活的解决方案,并且会导致打开的数据库句柄泄漏。在 resultRow
实现的情况下,泄漏游标也是如此。对于小型 Web 请求来说,这可能不是问题,但如果您尝试在更持久的应用程序中重用此代码,则会遇到问题。
目前最好坚持使用标准 PDO。
关于php - 使用 pdo 类不会返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25127485/