Tutorial :mysqli and php fetch object



Question:

I have the following code:

$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";     $results_latest = $mysqli->query($sql_latest);     while($row = $results_latest->fetch_object())   {    echo $row->id;   }  

How can I get the results into a array so I can do something like

echo $row[1]; echo $row[2]; echo $row[2];


Solution:1

I'm assuming you mean get all the rows in one array

$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";  $results_latest = $mysqli->query($sql_latest);  $rows = array();  while($row = $results_latest->fetch_object())  {      $rows[] = $row;  }    echo $rows[0]->id;  echo $rows[1]->id;  

Or, if you wanted the fields in the array:

while ($row = $results_latest->fetch_array()) {      echo $row[0];  //Prints the first column  }  


Solution:2

you are using $results_latest->fetch_object method
how do you think what method should be used to get an array?


Solution:3

mysql_fetch_assoc or mysql_fetch_array


Solution:4

$sql_latest = "SELECT * FROM tbl_latest ORDER BY id DESC LIMIT 0,3 ";     $results_latest = $mysqli->query($sql_latest);     while($row = $results_latest->fetch_array())   {    echo $row[0];   }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »