The code you have is correct. The fact that it does not return data may be due to:
- you are not connected to the database correctly
- there are really no records matching the criteria passed in
$nombre
.
- there is an error in the name of the table obtained through
self::TABLA
- there is an error in the name of the column
dec10
- that the column you are looking for is not declared as case insensitive (ci) 1
If you want to improve the code you can set the aforementioned controls in the code flow.
public static function buscarPorNombre($nombre){
$conexion = new Conexion();
if($conexion){
$consulta = $conexion->prepare("SELECT * FROM " . self::TABLA . " WHERE dec10 LIKE ?");
$like="%".$nombre."%";
if ($consulta->execute(array($like))){
$registros = $consulta->fetchAll();
$resultado = ($registros) ? $registros : array("error"=>"No se encontraron datos con el criterio $like");
}else{
$resultado=array("error"=>"Ocurrió el siguiente error en la consulta".$stmt->errorInfo()[2]);
}
}else{
$resultado=array("error"=>"No se pudo conectar a la base de datos. Revise el código de conexión");
}
return $resultado;
}
What the previous code does is to control the entire flow of the code, storing the eventualities in a variable called $resultado
. When something unexpected happens, the code will assign to this variable (which will always be an array) a key error
with the message of what happened. In this way, from the call to the function you can verify if the key error
exists in the result and choose or not to show the user the error message.
If there is no error, you would then process the data obtained in the query.
For example:
$findByName=TuClase::buscarPorNombre("pedro");
if (array_key_exists('error', $findByName)) {
echo $findByName["error"];
}else{
//Trabajar con los datos porque devolvió resultados
}
I hope it will be useful to you and anyone who reviews this question.
Notes:
1 We will not dwell too long on this issue, because it would stray too far from the general purpose of the question. However, a query with LIKE
could fail for that reason. If you want to explore this possibility, you can see the answer to the question: Can it be verified in DB if it is equal to a string? .