Reputation: 37
I am a beginner to codeIgniter and have looked for an answer to this on the CI forums and google, and even here...
OK I have searched for this and every time I find answers to this pertaining to use a foreach()
to get the data out of the array then do something with it in the foreach loop; this is not what i wish to do.
I am building a site whereby I would like to store site information, such as site title, description, abstract, keywords etc in a database table with just one row (rather than having to go to the html and do it there..)
So far I have something like this in my model:
function getAll(){
$q = $this->db->get('system');
if($q->num_rows() > 0){
return $q->row();
}
}
in my controller I have:
function index(){
$this->load->model("system_model");
$data[] = $this->system_model->getAll();
$this->load->view('home', $data);
}
and in my view I wish to have very simply (html tags are descriptive only):
<title><?php echo $this->title; ?></title>
<description><?php echo $this->description; ?></description>
As you can see a foreach loop would not work in this instance and I don't believe that the best way to do this is loop through the array in the controller and then pass each individual array part into the view as a separate variable..
Is this at all possible?
EDIT
I have given the tick to the first answer as that put me on the right track to find the solution (although it might not be 100% correct its working) in order to get this to work I followed answer number 1, but then in the view I did the following:
<title><?php echo$system[0]->title; ?></title>
Upvotes: 1
Views: 17673
Reputation: 1950
Here you go:
In your controller use:
function index(){
$this->load->model("system_model");
$data = $this->system_model->getAll();
$this->load->view('home', $data);
}
Your view will then look like this:
<title><?php echo $title; ?></title>
<description><?php echo $description; ?></decription>
Also, with your database query (in general) use result() as it sounds like you want more than one row:
function getAll(){
$q = $this->db->get('system');
if($q->num_rows() > 0){
return $q->result();
}
Upvotes: 0
Reputation: 239
Give the $data[] array a key name
function index(){
$this->load->model("system_model");
$data['mydata'] = $this->system_model->getAll();
$this->load->view('home', $data);
}
and in the view file you can echo or loop or whatever based on that key
echo $mydata
or
foreach($mydata as $md){
echo $md
}
The best way to query the database in the model is to do the following:
function get_user_by_id($id){
$this->db->where('id', $id);
$query = $this->db->get('users');
$result = $query->result_array();
return $result;
}
Upvotes: 2