Reputation: 23
i have been doing some php development for a project in class and i have encountered a problem.
The following function is supposed to return true when used with parameters i have entered myself, but it returns 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;
}
}
Where would seem to be the problem please ?
Upvotes: 1
Views: 54
Reputation: 91734
Your problem seems to be a combination of the query and the variables you bind:
The query is built like this:
// You use `=` to compare values
$request = $request.$clé." = :".$clé
And you bind your variables like this:
// You use `%` characters as if it is a `LIKE`
$statement->bindValue($clé, '%'.$val.'%');
^ ^ here you have a problem
You are using %
signs like you would be using wildcards in a LIKE
condition, but you are using =
.
Now your query is looking for literal strings that are surrounded by %
signs. Which (probably...) don't exist.
So either use LIKE
instead of =
or get rid of the %
characters where you bind the variables:
$statement->bindValue($clé, $val);
Upvotes: 1