我在一个用于验证用户凭据的类中有一个方法verifyCredentials。我正在重写它,以使用PHP的PDO,而不是DBMS依赖的mysqli语句。在获取绑定到准备好的查询的参数时,我遇到了困难。
PDO总是抛出警告
警告: PDOStatement::execute():SQLSTATEHY093:无效的参数号:绑定变量的数量与在线文件中的令牌数量不匹配
我显然错过了一些东西,但我不知道我的生活有什么意义。
代码片段,除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;
}
}发布于 2013-12-09 11:03:16
为了说明需要做什么,即使修复了前面建议的':alias'引号,MySQL关键字(如SELECT、INSERT)、表名和列名也不能通过占位符使用预先准备的语句绑定。为了动态创建MySQL查询,您必须以其他方式替换这些值。
我注意到您已经预先定义了SQL查询,所以使用类似于str_replace之类的东西,或者定义一个通用方法,它可以用如下所示的值替换这些占位符:
$sql = str_replace(array(
':userIdCol',
':pwdCol',
':usersTable',
':aliasCol'
), array(
$userIdCol,
$pwdCol,
$usersTable,
$aliasCol
), $this->queryGetPwdForUser);显然,在这种情况下,准备语句的方法是
$STH=$this->DBH->prepare($sql);
$STH->bindParam(':alias',$alias);https://stackoverflow.com/questions/20468545
复制相似问题