CodeIgniter Forums
displaying a single row in view - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: displaying a single row in view (/showthread.php?tid=62910)



displaying a single row in view - nady - 09-07-2015

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;
}
?>


RE: displaying a single row in view - PaulD - 09-08-2015

The documentation is excellent on this topic.

http://www.codeigniter.com/user_guide/database/results.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.


RE: displaying a single row in view - Wouter60 - 09-08-2015

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.