我在课堂上为一个项目做了一些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;
    }
}

请问问题出在哪里?

最佳答案

您的问题似乎是查询和绑定的变量的组合:
查询的构建方式如下:

// You use `=` to compare values
$request = $request.$clé." = :".$clé

你可以这样绑定你的变量:
// You use `%` characters as if it is a `LIKE`
$statement->bindValue($clé, '%'.$val.'%');
                             ^        ^ here you have a problem

您正在使用%符号,就像在LIKE条件下使用通配符一样,但您正在使用=
现在您的查询正在查找由%符号包围的文本字符串。可能(不……)不存在。
因此,要么使用LIKE而不是=,要么去掉绑定变量的%字符:
$statement->bindValue($clé, $val);

关于php - PDO Prepared语句即使MySQL语句也不会返回任何内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52856745/

10-11 06:39
查看更多