Welcome Guest, Not a member yet? Register   Sign In
displaying a single row in view
#1

Hi everbody

I want to send a single row from model to controller then from controller to view. i checked some of the same kind of question discussed earlier here but couldn't fix it
ERROR: Invalid argument supplied for foreach()
code for my controller is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class HomeController extends CI_Controller
{
public function index()
{
$this->load->database();
$this->load->model('select');
$data['cat'] = $this->select->select();
$data['top'] = $this->select->topmenu();
$data['title'] = $this->select->get_title('categories');
$this->load->view('HomeView', $data);
}
}
?>
------------------------Select.php(Model)----
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<?php
class Select extends CI_Model
{
public function select()
{
//data is retrive from this query
$query = $this->db->get_where('categories',array('category_name'=>'English'));
return $query->result();
}
public function topmenu()
{
$qry=$this->db->get('categories_name');
return $qry->result();
}
public function get_title($table,$where=NULL)
{
if(!empty($where))
{
$query = $this->db->get($table);
if($query->num_rows>0)
{
return $query->row();
}
else
{
return 0;
}
}
}
}
?>
------------------------HomeView----------------
<?php
foreach($title as $t)
{
echo $t->title;
}
?>
Reply
#2

The documentation is excellent on this topic.

http://www.codeigniter.com/user_guide/da...sults.html

The error is telling you that you do not have an appropriately formatted array for the foreach to loop through. You need to test result sets if there is any chance that you may not get any results from the search.

You could start by echoing your array with print_r and see what results you are actually outputting.

Best wishes,

Paul.
Reply
#3

Just skip the foreach part in your view.
If your model returns one row from the database ($query->row() ), then the result is a single object, not an array of objects.
If your model returns $query->result(), then it's an array that you can walk through with foreach.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB