The definition of fetch_array
says what next:
Get a row of results as an associative, numeric array, or
both.
Actually, when you execute query
a set of results is returned that must be read with one of the existing methods, among them fetch_array
. But you have to go through the results. If you use it without going row by row it will only return the first row, as in fact it is happening.
That is why, when you wait for multiple rows, you must open a loop that runs through the result set and put into an array (or printing directly if necessary) the different rows.
For example, we will read row by row using a while
loop:
$MDB = mysqli_connect( 'localhost', 'root', '',
'LOGIC' ) ;
$Q = mysqli_query( $MDB, "SELECT nombreAlumnos FROM
DATES" ) ;
while($row = mysqli_fetch_array($Q, MYSQLI_ASSOC);)
{
$a_y[] = $row;
}
Here your variable $a_y
will be an associative array with the data of each row.
To read it you can do something like:
foreach ($a_y as $row){
echo $row["nombreAlumnos"].PHP_EOL;
}
If you wanted a numerical array, you do it like this:
while($row = mysqli_fetch_array($Q, MYSQLI_NUM);)
{
$a_y[] = $row;
}
And the reading would be like this:
foreach ($a_y as $row){
echo $row[0].PHP_EOL;
}
Object-oriented style
As a last recommendation, I suggest you go through the object-oriented style, it's much clearer and much more modern:
$MDB = new mysqli("localhost", "root", "", "LOGIC");
$Q = $MDB->query("SELECT nombreAlumnos FROM DATES" );
while($row = $Q->fetch_array(MYSQLI_ASSOC))
{
$a_y[] = $row;
}
You can also use the methods directly:
-
fetch_assoc
: whenever you want an associative fix.
-
fetch_row
: whenever you want an array listed li>
-
fetch_all
: when you want to directly pass all results to an array. Here you do not need to open a loop. But this is not recommended when many results are expected because the memory could collapse . Also, this method only works if you have installed the driver mysqlnd
(see documentation in the link).