我从网上得到了一个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);
}
然后这里是我如何使用它在我的认证类的登录函数
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置于更合适的调试模式。这使得调试任何SQL问题更容易。
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
另外,我想评论一下,在PDO类中使用"当前"语句不是一个非常灵活的解决方案,并且会导致打开的数据库句柄泄漏。在resultRow
实现的情况下,泄漏游标也是如此。对于一个小的web请求来说,这可能不是问题,但如果你试图在一个更持久的应用程序中重用这段代码,你就会遇到问题。
目前最好还是使用标准的PDO。
你的PDO语法没问题,所以检查你的$user和$password和连接到DB
还有,用AND代替逗号会更好。