Get results from database in an array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Get results from database in an array

Post by Sindarin »

I am trying to create a function to get all results from the database and store it in an array so I can do this:

Code: Select all

$news_entries = $news->get_all();

echo $news_entries[1]['title_en']; //shows the title_en of the entry with id=1
echo $news_entries[1]['content_en']; //shows the content_en of the entry with id=1

echo $news_entries[4]['content_en']; //shows the content_en of the entry with id=4
so far I have this,

Code: Select all

$array = array();
$sql_result = $this->db_object->query("SELECT * FROM `".$this->entries_table."`");
while ($row = $this->db_object->fetch_array($sql_result)) {
	$array[$row['id']] = $row['title_en'];
}
		
return $array;
but it only returns title_en, nothing else. How can I add more columns to it? Or even better get all the columns for each row in the query?
Last edited by Sindarin on Wed May 30, 2012 7:24 pm, edited 1 time in total.
TylerH4
Forum Newbie
Posts: 10
Joined: Sat May 26, 2012 8:45 pm

Re: Get results from database in an array

Post by TylerH4 »

Just do:

Code: Select all

$array[$row['id']] = $row;
and that will give you the ability to access all of the columns returned by the database.
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Re: Get results from database in an array

Post by Sindarin »

Oh... it was that easy, it should make sense...yes.

I did this,

Code: Select all

$array = array();
while ($row = $this->db_object->fetch_row($sql_result)) {

	for($i=0;$i<$this->db_object->get_fields($sql_result);$i++) {
			$array[$row[0]][$this->db_object->get_field_name($sql_result, $i)] = $row[$i];
	}
}
		
$this->db_object->free_result($sql_result);
return $array;
but yeah works just... seems like a waste of time. xD
Post Reply