Help with Fetch_Array

0

I am practicing returning data from a database to my web page, with the FETCH ARRAY method. I would like to be able to return, for example, all the values of the NameAlumni field, but until now I have only managed to return the first value, and when I try to return the second one it returns the following field CorreosAlumnos ... My code:

$MDB = mysqli_connect( 'localhost', 'root', '', 
'LOGIC' ) ;

$Q = mysqli_query( $MDB, "SELECT nombreAlumnos FROM 
DATES" ) ;

$a_y = mysqli_fetch_array( $Q ) ;
ECHO ($a_y[0]); //ESTO RETORNA SOLO EL PRIMER NOMBRE (Edu).

I want you to return all the names in the NameAnnals field ... but when I increase a number to the array (like this: $ a_y [1]) it returns the following field or column (Correos) instead of alúmno number 2 .. And if I do this: $ a_y [0] [2] a letter of the first name comes back cut off, .

    
asked by user104554 24.10.2018 в 00:46
source

1 answer

0

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).
answered by 24.10.2018 в 01:37