When printing in json_encode an Array returned from a MySql query, the result is doubled:
first it shows the results based on the number array and then it shows it in array String
[
{
"0" : "Nombre",
"1" : "Apellido",
"idNombre" : "Nombre",
"idApellido" : "Apellido",
}
]
Query ::
$con = conexion();
$consulta = $con->prepare("select * from nombres where Nombre='$genero' order by Nombre asc");
$consulta->execute();
$resultado=$consulta->fetchAll();
return $resultado;
To print ::
$consulta=nombres::genero($_GET['Genero']);
echo json_encode($consulta);
Cause of the problem
This is due to the style of fetch that is being applied to the data.
If you read the documentation,
fetchAll()
(and the other PDO methodsfetch
can receive one of the fetch styles indicated here as a parameter .When none is indicated, PDO assumes the default method, which is
PDO::FETCH_BOTH
the one that returns the data in associative and numerical form, or the one that has the object set in the configuration (which can be done throughsetAttributes()
or in the fourth parameter (options) which you can pass in the constructor.Solution
The simplest way to solve this situation is to indicate
fetchAll()
which way you want the data.If you want them as associative array:
In this case the results would be:
If you want it as a numeric array:
In this case the results would be:
It is clear that the way of reading
$resultado
will vary depending on the style you use...Security Recommendation
Your query is highly vulnerable to SQL Injection attacks . As a rule, never pass variables in queries. A malicious user can manipulate it and cause irreparable damage at various levels of your system, not just the database.
In PDO it is relatively easy to shield the code:
The prepared query in this case consists of changing the value that you passed directly through a marker
?
and the data is passed in the form of an array in the methodexecute()
. That way PDO will neutralize any attempted attack.