I am currently following tutorials on viewing data from the database using the Framework Codeigniter. There are various ways in which I've learnt. Is there is a more realiable way- either displaying as an array or using 'foreach' in the view file? Any opinions would be helpful.
This is my code using the two methods:
Method 1 Model:
function getArticle(){
$this->db->select('*');
$this->db->from('test');
$this->db->where('author','David');
$this->db->order_by('id', 'DESC');
$query=$this->db->get();
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}$query->free_result();
}
}
Method 1 View file:
<?php foreach($article as $row){ ?>
<h3><?php echo $row->title; ?></h3>
<p><?php echo $row->content; ?></p>
<p><?php echo $row->author; ?></p>
<p><?php echo $row->date; ?></p>
<?php } ?>
Method 2 Model:
class News_model extends CI_Model {
function getArticle(){
$this->db->select('*');
$this->db->from('test');
$this->db->where('author', 'David');
$this->db->order_by('id', 'DESC');
$query=$this->db->get();
if ($query->num_rows()>0) {
return $query->row_array();
}
$query->free_result();
}
Method 2 View file:
<?php echo '<h3>' .$article['title'].'</h3>' ?>
<?php echo '<p>' .$article['content']. '</p>' ?>
<?php echo '<p>' .$article['author']. '</p>' ?>
<?php echo '<p>'. $article['date']. '</p>' ?>
I would do it like that:
Model
function getArticle() {
$this->db->select('*');
$this->db->from('test');
$this->db->where('author','David');
$this->db->order_by('id', 'DESC');
return $this->db->get()->result();
}
}
Controller
function get_tests() {
$data = array(
'tests' => $this->mymodel->getArticle()
}
$this->load->view('myview', $data);
}
View
<table>
<?php foreach($tests as $test) { ?>
<tr>
<td><?php echo $test->title;?></td>
<td><?php echo $test->content;?></td>
<td><?php echo $test->author;?></td>
<td><?php echo $test->date;?></td>
</tr>
</table>
If you wish to work with arrays rather than objects, in your model change line
return $this->db->get()->result();
to
return $this->db->get()->result_array();
and in views echo like
<td><?php echo $test['title'];?></td>
P.S.
In your code you use $query->free_result(); but it doesn't even run because when you use keyword return everything after that is not even parsed. It's not necessary to free results anyway.
P.S.2.
You use if($query->num_rows() > 0) { but don't have the else part, it means that it's not necessary too. If you'll return no lines to your foreach statement in the view, you won't get any errors.
Related
I am super stuck on a problem. I went through many solution give here related to this but I did not found any solution to my error.
this is the error message I am facing and I used print_r to view what is the output but is also a dead end.
My controller - Search.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Search extends CI_Controller {
function index(){
$this->load->model("ModSearch");
$data["get_ztable"] = $this->ModSearch->get_zscore();
$data["get_course"] = $this->ModSearch->getCourse();
$data["get_stream"] = $this->ModSearch->getStream();
$data["get_district"] = $this->ModSearch->getDistrict();
$data["get_uni"] = $this->ModSearch->getUniversity();
$this->load->view('addZscore',$data);
}
Model - ModSearch.php
public function get_zscore(){
$query = $this->db->get('tbl_zscore');
return $query;
}
View - addZscore.php
<table style="width:50%">
<tr>
<th>Z ID</th>
<th>Z Score</th>
</tr>
<?php echo print_r($get_ztable);?>
<?php
if($get_ztable->num_rows() > 0)
{
foreach ($get_ztable as $row)
{
?>
<tr>
<td><?php echo $row->z_id; ?></td>
<td><?php echo $row->z_score; ?></td>
</tr>
<?php
}
}else{
echo 'Database Error(' . $this->db->_error_number() . ') - ' . $this->db->_error_message();
}
?>
</table>
You have to make changes in your model function that must return a "result" that you can easily use in your view. So just replace
return $query
with
return $query->result()
Or make a change in your foreach loop in views from
foreach($get_ztable as $row)
to
foreach($get_ztable->result() as $row)
I have a table that store the data of ID, ID Login, Name, etc. But i just want to show the data based on ID Login
Here My Controller :
function index(){
$data['hasil'] = $this->M_user_lapor->index_model();
$this->load->view('v_user_lapor/index', $data);
}
My Model :
function index_model(){
$baca = $this->db->query('select * from user_lapor');
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}
View :
<tbody>
<?php
if ($hasil){
$no = 1;
$array = json_decode($hasil, true);
foreach($array as $data) {
?>
<tr>
<td class="text-center"><?php echo $no++;?></td>
<td><?php echo $data['nm_unit'];?></td>
<td><?php echo $data['pic_1'];?></td>
<td><?php echo $data['pic_2'];?></td>
<td><?php echo $data['ip_wan'];?></td>
<td><?php echo $data['ip_lan'];?></td>
<td><?php echo $data['prov'];?></td>
<td><?php echo $data['icn_sid'];?></td>
<td><?php echo $data['tlkm_sid'];?></td>
</tr>
<?php
}
}
?>
</tbody>
As you can see, there is id_login inside my model, and i want to show the table data based on it, hopefully somebody can help me because i'm just using the codeigniter, thnaks
I solved this by myself, lol. I just pass the id_login value from session, so i add this to my controller :
function index(){
$id_login = $this->session->id_login;
$data['hasil'] = $this->M_user_lapor->index_model($id_login);
$this->load->view('v_user_lapor/index', $data);
}
And call it to my model :
function index_model($id_login){
$baca = $this->db->query('select * from user_lapor where id_login='.$id_login);
if($baca->num_rows() > 0){
foreach ($baca->result() as $data){
$hasil[] = array(
'id_login'=>$data->id_login,
'id_lapor'=>$data->id_lapor,
'nm_unit'=>$data->nm_unit,
'pic_1'=>$data->pic_1,
'pic_2'=>$data->pic_2,
'ip_wan'=>$data->ip_wan,
'ip_lan'=>$data->ip_lan,
'prov'=>$data->prov,
'icn_sid'=>$data->icn_sid,
'tlkm_sid'=>$data->tlkm_sid,
'status'=>$data->status,
);
}
return json_encode ($hasil);
}else{
return false;
}
}
In database table there is no rows means getting error Undefined variable: results using codeigniter,in case there is no row or empty table is there means i want to display view page
controller
$data['breview'] = $this->Profile_model->review();
$this->load->view('supplierreview', $data);
Model
public function review() {
$this->db->select('*');
$this->db->from('reviews');
$this->db->join('supplier_otherdetails', 'supplier_otherdetails.supplierid_fk = reviews.supplier_id');
$this->db->join('customer_registration', 'reviews.customer_id=customer_registration.id');
$this->db->join('sub3_category', 'reviews.product_id=sub3_category.id');
$this->db->where('supplierid_fk', $this->session->id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
}
view page
<?php
foreach ($breview as $row) {
?>
<div class="reviewsection">
<img src="<?php echo 'data:image;base64,' .$row->product_image; ?>" class="img-circle img-user" alt="" width="50px;" height="50px;"/>
<span class="starfont"><botton class="btn btn-danger"> <?php echo $row->ratings; ?> <span class="fa fa-star starfont"></span></botton> </span>
<div class="content-left">
<p><b>Product Name:<?php echo $row->product_name; ?></b></p>
<p><?php echo $row->review_msg; ?></p>
<?php $buyer_review = strtotime($row->review_date);?>
<?php $date=date('d-F-Y',$buyer_review); ?>
<p>Buyer Name : <?php echo $row->first_name; ?> <?php echo $date ; ?></p>
</div>
</div>
<?php } ?>
$results is not defined.
Please add $results = [];
Here you go:
$results = [];
if ($query->num_rows() > 0) {
$results = $query->result();
}
return $results;
In my model, in most cases, i do the following
public function my_function() {
//$qry = YOUR_QUERY
if ($qry->num_rows() > 0) //or ==1 or whatever, depends on your structure
return $qry->result_array(); // or row_array, depends on your structure
return FALSE;
}
Then in your controller you can check if the result is FALSE or EMPTY like:
$result_from_model = $this->my_model->my_function();
if($result_from_model && !empty($result_from_model)) {
//your code here
}
You can use the following code :
return (is_array($results)?$results:array());
Hope it works.
All the answers given so far are good. Here is yet another way to do it. It's essentially the same as the accepted answer only using a ternary instead of if.
$query = $this->db->get();
return $query->num_rows() > 0 ? $query->result() : array();
}
Hello all I have a problem that my information is not being send to my view file.
What mistake do I have?
My Model:
public function viewbds($duanid, $bdsid)
{
$q = $this->db->query("SELECT bds.tenduan, bds.id, bds.tieude FROM bds WHERE bds.tenduan=$duanid AND bds.id=$bdsid);
if($q->num_rows() > 0)
return $q->result();
return false;
}
My Controller:
public function chothue($duanid, $bdsid)
{
$this->load->model('admin_model');
$date[chothue] = $this->admin_model->viewbds('$duanid', '$bdsid');
$this->load->view('admin/view', $data);
}
My View: admin/chothue/1/1
<?php foreach($chothue as $d) { ?>
<tr>
<td><?php echo $d->id; ?></td>
<td><?php echo $d->tenduan; ?></td>
<td><?php echo $d->tieude; ?></td>
<?php } ?>
$this->db->query("SELECT bds.tenduan, bds.id, bds.tieude FROM bds WHERE bds.tenduan=$duanid AND bds.id=$bdsid")->get();
Don't forget to use ->get()
AND use active record
$this->db->select("tenduan, id, tieude")->from("bds")->where("tenduan", $duanid)->where("id", $bdsid)->get();
I have another error anymore, when I try to display a result in my view, the result is NULL and I can't see the result of my query at models.
Here's my code list :
on the controller (home.php) :
$data['hasil5'] = $this->home_model->popular_list();
on the model (home_model.php) function popular_list() :
function popular_list($limit=2)
{
$this->db->select('news.*');
$this->db->where('id',$this->uri->segment(3));
$this->db->where('publish',1);
$this->db->where('viewed >= ',5);
$this->db->order_by('id','DESC');
$this->db->limit($limit);
$query = $this->db->get('news');
return $query->result();
} //thanks to kumar_v
and on my view (home.php) as a part of "Popular news" :
<h2>Most Popular News :</h2>
<?php
foreach ($hasil5 as $data5):
?>
<div class="welcome clear"><img class="imgl" src="<?php echo base_url(); ?>assets/news/original/<?php echo $data5->image; ?>" alt="" height="119" width="125" />
<div class="fl_right">
<h2><?php echo anchor($data5->kategori.'/detail/'.$data5->id,$data5->title) ?></h2>
<p><?php echo $data5->sinopsis; ?></p>
</div>
</div>
<?php
endforeach;
?>
The results is NULL, can you correct it again? thanks..
try this :
function popular_list($limit = 2) {
$query = $this->db->select('*')
->where('id',$this->uri->segment(3))
->where('publish',1)
->where('viewed >= ',5)
->order_by('id','DESC')
->limit($limit)
->get('news');
print_r($query->result());
return $query->result();
}
You can put the whole thing in $query variable. And also, you can improve your $this->db->where() by putting the params in an array.
You should fix your code to look like so:
<?php
foreach ($data['hasil5'] as $data5):
?>
You were using the wrong variable in your foreach loop.
Checking if the query will return any row is a good idea.
function popular_list($limit=2)
{
$result = null;
$this->db->select('news.*');
$this->db->where('id',$this->uri->segment(3));
$this->db->where('publish',1);
$this->db->where('viewed >= ',5);
$this->db->order_by('id','DESC');
$this->db->limit($limit);
$query = $this->db->get('news');
if($query->num_rows() > 0)
{
$result = $query->result();
}
return $result;
}