How to access multiple rows in SQL from php

0

When I make a query to a table that results in two rows, for example:

$sql= "SELECT id, nombre, apellido FROM usuarios WHERE nombre = 'Juan'";
$res = $db->query($sql) or die("error: ".$sql);
$row = $res->fetch_assoc();

and I get this result;

id: 1 nombre: Juan apellido: Rodriguez
id: 5 nombre: Juan apellido: Herrero
id: 8 nombre: Juan apellido: Fuentes

How can I access all this data from php? because I can only access the first record using $row['id'] $row['nombre'] $row['apellido']

    
asked by Pavlo B. 15.12.2016 в 13:06
source

2 answers

4

Your variable $row saves ALL the results, what you should do is something like this:

$res = $db->query($sql) or die("error: ".$sql);
$results = array();
while($row = mysql_fetch_assoc($res)) {
   $results[] = $row;
}

And to get all the data

foreach ($results as $result){
   print_r($result['id']);
   print_r($result['nombre']);
}

How you want to access through an "index" to your object would be enough with this:

$array_final = array();
foreach ($results as $result){
   $array_final[] = $result;
}

for ($i=0; $i < count($array_final); $i++) { 
   print_r($array_final[$i]['nombre']);
}
    
answered by 15.12.2016 / 13:10
source
1

Actually you can get the data from the results:

$res = $db->query($sql) or die("error: ".$sql);
$results = array();
while($row = mysql_fetch_assoc($res)) {
   print_r($row['id']);
   print_r($row['nombre']);
}

If you are only going to read the data once, I think that this way it can serve you, instead if you want to read the result of the selection several times, it is better as the partner @sioesi says.

Also a ResulSet can be reset with mysqli_data_seek($res, 0); mysqli_data_seek

    
answered by 15.12.2016 в 14:29