With this code you can print the name of the first four records of the result set:
$i=0;
do{
echo $fila["Nombre"]."<br>";
$i++;
} while($i < 5 && $fila = mysqli_fetch_assoc($result));
Consists of reading them within a loop do... while
which will end when the counter is less than 5
, that is, when it reaches the record 4
.
Note that I used mysqli_fetch_assoc
because fetch_array
produces two values (one associative and one numerical) for each column, which does not seem convenient from the point of view of optimization.
Attention to this
Keep in mind that while
will iterate over your result set and if you stop it in record number 4, if for some reason you try to recover data again, the results pointer will be where you stopped it.
If you put twice the code of the do ... while
of above you will see that in the second part it will print again four records, but starting with the last one, where the pointer remained.
If you want to use your data in several scenarios, you can then retrieve them all in one array and then use that array to read them in those different parts.
For example:
while ($row = mysqli_fetch_assoc($result)){
$arrDatos[]=$row;
}
/*Puedes cerrar el conjunto de resultados*/
$result->close();
There is in $arrDatos
all results, not dependent on the pointer of the result set, which you can close and use $arrDatos
later.
For example, to read the first four you can do it like this:
$i=0;
do{
echo "-".$arrDatos[$i]["Nombre"].PHP_EOL;
$i++;
} while($i < 5 && $arrDatos);
Or with a foreach
loop:
$i=0;
foreach ($arrDatos as $row){
$i++;
echo $row["Nombre"].PHP_EOL;
if ($i==4){ break;}
}
And if it offers to read all the data:
foreach ($arrDatos as $row){
echo $row["Nombre"].PHP_EOL;
}
EDITION
If you want to create variables using specific rows, you can access each row by the index of $arrDatos
and then by the key, Nombre
in this case.
For example:
$nameOne = $arrDatos[0]["Nombre"]; //Posición 0 o fila 1
$nameTwo = $arrDatos[1]["Nombre"]; //Posición 1 o fila 2
$nameThree = $arrDatos[2]["Nombre"]; //Posición 2 o fila 3
Etc.
There three variables were created with the names of the first three people in the array. We are always assuming that that column is called Nombre
in your database. If not, you must put the name you have to make it work.