Welcome Guest, Not a member yet? Register   Sign In
Get results from model to controler and show in view
#1

[eluser]exodus7[/eluser]
Hey guys - newbie here to MVC, PHP and CodeIgniter:

I'm having trouble getting the results from my model into my view. What I was trying to do was call a model from the controller to perform a function and then display the result in my view. Here is what I got so far:

Model:
Code:
function getGender()
{
$query = $this->db->query('SELECT COUNT(*) FROM survey_results WHERE gender = "m"');
return $query->result();
}
Controller:
Code:
function survey_results()
{
$this->surveymodel->getGender($_POST);
$data['result'] = $this->surveymodel->getGender('survey_results');
$this->load->view('survey/results', $data);            
}
View:
Code:
<?=
$result;
?>

I don't get any errors - the view says "Array" rather than the value
#2

[eluser]Unknown[/eluser]
Try running var_dump($result);

You'll see that even though the database returned just one item (your count), $result is a little bit more complicated. The fact that you only needed one field from one row means that $query->row() is probably what you want instead of $query->result()

You probably also want to tweak your query a bit: SELECT COUNT(*) AS Num FROM ...

That way you can refer to the count more easily, and do this within survey_results():

$row = $query->row();
return $row->Num;

Then $data['result'] will contain your actual number, like you're expecting it to.
#3

[eluser]exodus7[/eluser]
That did the trick - Thanks for the help!
#4

[eluser]exodus7[/eluser]
One more question, If I have multiple rows as a result, I would use $query->result() ?

So would Model would look like this?

Code:
function q10()
    {
       $query = $this->db->query('SELECT q10 FROM survey_results');
        return $query->result();
    
    }

What would the controller and view look like?
#5

[eluser]Edemilson Lima[/eluser]
[quote author="erikv4" date="1198301274"]Try running var_dump($result);

You'll see that even though the database returned just one item (your count), $result is a little bit more complicated. The fact that you only needed one field from one row means that $query->row() is probably what you want instead of $query->result()[/quote]

If you use GROUP BY in your query, the database will return one row for the total of each group. In this case, it is necessary to fetch all the rows and sum the subtotals to get the the real total rows returned by the query. Example:

Code:
$records=mysql_num_rows($result);
if($records==1) { // no groups where used
  $row=mysql_fetch_array($result);
  $num_rows=intval($row[0]);
  return $num_rows;
} elseif($records>1) { // query with group
  $total_rows=0;
  while($row=mysql_fetch_array($result)) {
    $total_rows+=intval($row[0]);
  }
  return $total_rows;
}




Theme © iAndrew 2016 - Forum software by © MyBB