Is that by doing so:
$array= array("Dni" => $fila[0],"Nombre"=> $fila[1],"edad"=> $fila[2]."\n");
You are replacing the array value in each pass of the loop.
You should do it like this:
$array []= array("Dni" => $fila[0],"Nombre"=> $fila[1],"edad"=> $fila[2]);
The \n\
does not make any sense in the array.
It is also not necessary to declare the variable $array
at the beginning.
Although the best way to do this is with fetch_assoc
that creates a associative array whose keys are the column names. That way you pass each row directly to the array without having to type the key names manually.
Example:
if ($resultado = mysqli_query($conexion2, $consulta)) {
/* obtener el array por índices */
while ($fila = mysqli_fetch_assoc($resultado)) {
$array []= $fila; //La declaración de $array arriba no es necesaria
}
/*Aquí puedes ver tu resultado*/
print_r ($array); //La salida aquí es sólo para depurar.
}
If you want to show some data on the screen within the same while
. Making $fila["nombre-columna"]
access each value:
if ($resultado = mysqli_query($conexion2, $consulta)) {
/* obtener el array por índices */
while ($fila = mysqli_fetch_assoc($resultado)) {
echo "DNI: ".$fila["dni"]."\n";
echo "Nombre: ".$fila["nombre"]."\n";
echo "Edad: ".$fila["edad"]."\n";
}
}
If you want to read it outside the while
:
VERY IMPORTANT: Remove the statement above: $array=array()
; If you have not removed it, you will be creating an array of arrays.
if ($resultado = mysqli_query($conexion2, $consulta)) {
/* obtener el array por índices */
while ($fila = mysqli_fetch_assoc($resultado)) {
$array []= $fila; //La declaración de $array arriba no es necesaria
}
/*Aquí puedes ver tu resultado*/
foreach ($array as $k=>$v){
if (is_array($v)){
foreach ($v as $kk=>$vv){
echo $kk." - ".$vv."\n";
}
}else{
echo $k." - ".$v;
}
}
}
The problem is that mysqli, I do not know why, unlike PDO, it creates an array of array, so you have to read the values within two foreach
.
Or, as you have said @ D.Bulten, you can read it with a% co-count%:
for ($i=0; $i<count($array); $i++) {
echo $array[$i]['dni']."\n";
echo $array[$i]['nombre']."\n";
}