tags:

views:

40

answers:

4

Hi,

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];

+1  A: 

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
}
ircmaxell
perfect thanks, I thought it was something along those lines, I just testing the waters with mysqli and oop so forgive the noob question. However is their a better way to do this ?
Oliver Bayes-Shelton
Is there a better way to do what? You need to explicitly define what you want to do before you (or anyone else for that matter) can tell if there is a better way... Oh, and there is no reason to ask for forgiveness. We all were new at one point, and we all need to learn. You're at least asking, which is the second best way to learn (the best way is to teach/answer questions)...
ircmaxell
put the rows into one array so I can print the specific result
Oliver Bayes-Shelton
That's about how it's done just about everywhere I've seen (declare an array first, use a while loop to fetch each row, and store that row in the array)... Most times, people will put that logic into a database "abstraction" (more of a helper) layer/class. It's up to you if you want to find one, but I'd suggest building your own as there's a lot to learn from building things (Especially relatively simple things such as a DB class)...
ircmaxell
Do you have a link which will help me learn to build one ? Or should I look on the php manual for a specific thing ? Im working on my first oop app at work so its quite new but I thought I had to get into this whole mysqli and oop stuff sooner rather than later .
Oliver Bayes-Shelton
A: 

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

Col. Shrapnel
A: 

mysql_fetch_assoc or mysql_fetch_array

fabrik
A: 
$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];
 }
Robus