Codeigniter return one row from database

Hello.

I have this simple function in PHP Codeigniter where I am tryign to get a single row from the database in return it to the controller as an array, but I can’t manage to do it for some reason.
This is the function:

    function getquestions(){
	
	$query = $this->db->get('questions');
	$maxrows = $query->num_rows();
	$randNum = rand(0,$maxrows);

	$question = $this->db->get_where('questions', array('id' => $randNum));

	return $question;
    
}

I understand that the query returns an array. Why can’t I return it?

Ok. This should work:

 function getquestions(){
	$questionresults = array();

	$query = $this->db->get('questions');
	$maxrows = $query->num_rows();
	$randNum = rand(0,$maxrows - 1);

	$question = $this->db->get_where('questions', array('id' => $randNum));

	foreach ($question->result() as $row) {
		$questionresults[1] = $row->question;
		$questionresults[2] = $row->image;
		$questionresults[3] = $row->answer1;
		$questionresults[4] = $row->answer2;
		$questionresults[5] = $row->answer3;
		$questionresults[6] = $row->answer4;
		
	}
	return $questionresults;

	
}

Try adding this to temporarily display the values.

echo  '<pre>';
var_dump( $question-result() );

var_dump( $questionresults );

echo '</pre>';
die; 

return $questionresults;

Don’t you want return $question->row(); ?

Observations:

  1. The above query will only return a single row with an id = $randNum
  2. The foreach() loop is not necessary
  3. Nothng is assigned to $questionresults[0] ???
  4. Results could have been returned using $query->result_array();

See CodeIgniter’s excellent documentation usually with clear examples"

http://www.codeigniter.com/user_guide/database/results.html#result-arrays

As @WebMachine mentioned it is easier to obtain the results of a single row using:

  $row = $question->row(); 
     $questionresults[1] = $row->question;
     $questionresults[2] = $row->image;
     $questionresults[3] = $row->answer1;
     $questionresults[4] = $row->answer2;
     $questionresults[5] = $row->answer3;
     $questionresults[6] = $row->answer4;

// Alternatively  include id
     $questionresults[] = $row->id;
     $questionresults[] = $row->question;
     $questionresults[] = $row->image;
     $questionresults[] = $row->answer1;
     $questionresults[] = $row->answer2;
     $questionresults[] = $row->answer3;
     $questionresults[] = $row->answer4;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.