我一直在为类里面的一个项目做一些 php 开发,我遇到了一个问题。
以下函数在与我自己输入的参数一起使用时应该返回 true,但它返回 false:
public function check_if_in($table, $condition){
$request="SELECT *"; // Selecting one column
$request=$request.' FROM '.$table.' WHERE '; // From the table i want to check in
$keys = array_keys($condition);
foreach($condition as $clé=>$val){
if(!($clé == end($keys))){ // If it's not the last condition
$request = $request.$clé." = :".$clé." AND "; // add AND
}
else{
$request = $request.$clé." = :".$clé.";"; // Add a semicolon
}
}
try {
$statement = $this->pdo->prepare($request); // Prepare the statement
}
catch (PDOException $e){
die("Erreur array :" . $e->getMessage());
}
foreach($condition as $clé=>$val) {
$statement->bindValue($clé, '%'.$val.'%'); // Binding all the parameters
}
try {
$statement->execute();
}
catch (PDOException $e){
die("Error :" . $e->getMessage());
}
if($statement->rowCount() > 0){
return true;
}
else {
return false;
}
}
请问问题出在哪里?
最佳答案
您的问题似乎是查询和您绑定(bind)的变量的组合:
查询是这样构建的:
// You use `=` to compare values
$request = $request.$clé." = :".$clé
然后你像这样绑定(bind)你的变量:
// You use `%` characters as if it is a `LIKE`
$statement->bindValue($clé, '%'.$val.'%');
^ ^ here you have a problem
您正在使用 %
符号,就像您在 LIKE
条件中使用通配符一样,但您使用的是 =
。
现在您的查询正在寻找被 %
符号包围的文字字符串。哪个(可能...)不存在。
因此,要么使用 LIKE
而不是 =
,要么去掉绑定(bind)变量的 %
字符:
$statement->bindValue($clé, $val);
关于php - PDO Prepared statement 即使 MySQL Statement 也没有返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856745/