【发布时间】:2013-12-26 10:33:07
【问题描述】:
我在一个用于验证用户凭据的类中有一个方法 verifyCredentials。我正在重写它以使用 PHP 的 PDO 而不是依赖于 DBMS 的 mysqli 语句。我无法将参数绑定到我准备好的查询。
PDO 总是抛出警告
警告:PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: 绑定变量的数量与 [line] 上 [file] 中的标记数量不匹配
我显然在这里遗漏了一些东西,但我无法弄清楚我的生活是什么。
代码 sn-p,除了 DBH 和 STH 之外的所有内容都由外部 constants.php 文件定义:
class FancyClass{
function __construct(){
try{
$this->DBH=
new PDO(PDO_DRIVER.':host='.DB_HOST.';dbname='.DB_DB,
DB_USER, DB_PWD);
}
catch(PDOException $e){
return $e->getMessage();
}
$this->queryGetPwdForUser="select :userIdCol , :pwdCol from :usersTable where :aliasCol = ':alias' limit 1"
}
function __destruct(){
$this->DBH=null;
}
function verifyCredentials($alias,$pwd){
$STH=$this->DBH->prepare($this->queryGetPwdForUser);
$STH->bindParam(':userIdCol',$userIdCol);
$STH->bindParam(':pwdCol',$pwdCol);
$STH->bindParam(':usersTable',$usersTable);
$STH->bindParam(':aliasCol',$aliasCol);
$STH->bindParam(':alias',$alias);
$userIdCol=DB_COLUMN_USERID;
$pwdCol=DB_COLUMN_USERPWD;
$usersTable=DB_TABLE_USERS;
$aliasCol=DB_COLUMN_USERALIAS;
$STH->execute();
$result=$STH->fetch();
if($result==false) return false;
$hasher = new PasswordHash(50,false);
if($hasher->CheckPassword($pwd,$result[DB_COLUMN_USERPWD]))
return $result[DB_COLUMN_USERID];
else
return false;
}
}
【问题讨论】:
-
即使你已经像
Let me see下面建议的那样修复了它,你也不能使用准备好的语句将 mysql 关键字、表或列绑定到占位符。您首先必须像$sql = "SELECT $userIdCol,$pwdCol FROM $usersTable WHERE $aliasCol = :alias";这样创建一个 SQL 字符串查询,在这种情况下,您将只能绑定:alias值。