I am wanting to make a request to a postgres db with php but it throws me the following error:
"SQLSTATE[42601]: Syntax error: 7 ERROR: error de sintaxis al final de la entrada\nLINE 1: SELECT * FROM public.interesado WHERE 1=1 AND \n
The code of interested.model.php is the following:
public static function buscarInteresado($data)
{
try {
$sql = "SELECT * FROM public.interesado WHERE 1=1 AND ";
$stmt = Connection::getConnection()->prepare($sql);
$params = [];
foreach(['nombre','apellido'] as $campo) {
if(!empty($data[$campo])) {
$sql .= sprintf(' AND %s = :%s ',$campo, $campo);
$params[$campo] = $data[$campo];
}
}
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $th) {
return ['error'=> $th->getMessage()];
}
}
The function is to search for an interested party by first or last name, or both.
I had to adjust the code a bit.
Leaving the code like this:
If the idea is to search by name and/or surname yes or yes, it is not useful to start your query in this way:
Because if there are no parameters you will be sending an empty query to the handler. It is better to control the situation of the data.
Here we will do it by means of an array called
$where
, we will fill it when there is data and then we will verify it and only then we prepare and execute the query: