Reputation: 684
I am a newbie to Codeigniter framework, I have created a simple app that will fetch data from database and then display with condition in Views. I'm trying to display specific data from database to my View, So far, I have no luck using the code below.
Model (Datamodel.php)
function getData() {
$this->db->select("name, value");
$this->db->from('settings');
$query = $this->db->get();
return $query->result_array();
}
Controller (maincontroller.php)
function index()
{
$data['metadata'] = $this->Datamodel->getData();
$this->load->view('viewdata', $data);
}
View
<h3>Site Information</h3>
<?php foreach($metadata as $data) {?>
<h4>Site Title: <?php echo $data['site_title']; ?></h4>
<h4>Site Description: <?php echo $data['site_description']; ?></h4>
<h4>Site keyword: <?php echo $data['site_keyword']; ?></h4>
<h4>Site Year: <?php echo $data['site_year']; ?></h4>
<?php }?>
I want to display something like these on browser:
Site Title: My first codeigniter app
Site Description: This is sample ci application
Site keyword: simple ci app, first app
Site Year: 2015
{ Any help & suggestion is accepted. thanks! pls see this image [ http://prntscr.com/722hsm ] for my database structure !}
Upvotes: 0
Views: 8152
Reputation: 23948
Appreciate that you are taking initiative.
Just some modifications:
Model
<?php
function getData() {
$siteData = array();
$this->db->select("name, value");
$this->db->from('settings');
$query = $this->db->get();
if ($query->num_rows()) {
foreach ($query->result_array() as $row) {
// Your data is coming from multiple rows, so need to loop on it.
$siteData[$row['name']] = $row['value'];
}
}
return $siteData;
}
View:
<h3>Site Information</h3>
<?php foreach($metadata as $dataName => $dataValue) {?>
<!-- You are getting the names and values in loop, so,
use it in loop. Also, use ucwords() and str_replace() to beautify your
output. for more informtion on this, read php.net documentation.
-->
<h4><?php echo ucwords(str_replace('-', ' ', $dataName))?>: <?php echo $dataValue; ?></h4>
<?php }?>
SECOND APPROACH (WITHOUT FOREACH):
<h3>Site Information</h3>
<h4>Site Title: <?php echo $metadata['site_title']; ?></h4>
<h4>Site Description: <?php echo $metadata['site_description']; ?></h4>
<h4>Site keyword: <?php echo $metadata['site_keyword']; ?></h4>
<h4>Site Year: <?php echo $metadata['site_year']; ?></h4>
Upvotes: 1
Reputation: 4110
Just load your model in controller:
function index()
{
$this->load->model('Datamodel');
$data['metadata'] = $this->Datamodel->getData();
$this->load->view('viewdata', $data);
}
try this on your views
<h3>Site Information</h3>
<h4>Site Title: <?php echo $metadata['site_title']; ?></h4>
<h4>Site Description: <?php echo $metadata['site_description']; ?></h4>
<h4>Site keyword: <?php echo $metadata['site_keyword']; ?></h4>
<h4>Site Year: <?php echo $metadata['site_year']; ?></h4>
Upvotes: 1