I have the following code to search by name and then the data found is passed to an array in JSON.
Should I first receive the query with a mysql_fetch_array()
and then pass it to a JSON with mysqli_fetch_assoc()
?
What am I doing wrong in my code?
<?php
include_once "conexion.php";
if(!empty($_POST))
{
if(empty($_POST['nombre'])){
}else{
$nombre = $_POST['nombre'];
$consulta = mysqli_query($conexion,"SELECT * FROM clientes1
WHERE nombre = '$nombre'");
while ($resultado = mysqli_fetch_assoc($consulta)){
$nombre_resultado[] = $resultado;
}
echo json_encode($nombre_resultado,JSON_UNESCAPED_UNICODE);
}
}
?>
To begin with, I must warn you that your code suffers from serious security problems associated with SQL injection , which must be solved with prepared queries or using
mysqli_real_escape_string()
.To continue, it is not necessary to nest a check a
$_POST
before checking the existence of one of its indexes.You're also using an unnecessary loop to get all the records from the query. They can all be obtained with a single call to
mysqli_fetch_all()
(if you're using the controllermysqlnd
).Also, as @A. Cedano in the comments, you are missing error checks before calling
mysqli_fetch_assoc()
(ormysqli_real_escape_string()
as I propose).An example of the corrected code could be: