I tried to get some records from database, like a ticket system, it's a code which downloading from database results
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$query = $this->db->get();
if($query->num_rows() > 0) {
$row = $query->row_array();
return $row;
}
But it's duplicating results, and not showing all results, but only one.
there is result
Try this
Method 01
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)) # this will act as $query->num_rows() > 0
{
return $result;
}
Method 02
$this->db->select('*');
$this->db->from('tickets');
$this->db->where('t_author_steam_id', $steamid);
$this->db->group_by('t_author_steam_id'); # add this
$query = $this->db->get();
$result = $query->result_array();
if(!empty($result)) # this will act as $query->num_rows() > 0
{
return $result;
}
In view
<?php foreach($tickets as $items){ ?>
<tbody>
<th scope="row"><?php echo $items['t_id']; ?></th>
<th scope="row">
<?php if($items['t_lang'] == 1)
{
echo lang('polish');
} elseif($items['t_lang'] == 2) {
echo lang('english');
} ?>
</th>
<td><?php echo $items['t_title']; ?></td>
<td><?php echo $items['t_date']; ?></td>
<td>
<?php
if($items['t_status'] == 1)
{
echo '<span class="label label-info" id="status">'.lang('items-status-1').'</span>';
}
elseif($items['t_status'] == 2)
{
echo '<span class="label label-warning" id="status">'.lang('items-status-2').'</span>';
}
elseif($items['t_status'] == 3)
{
echo '<span class="label label-Success" id="status">'.lang('items-status-3').'</span>';
}?>
</td>
<td>Zobacz</td>
</tbody>
<?php } ?>
Method 1 is works fine. Problem is with in your code where you use foreach loop
$query->row_array() returns only the first row of all the records. If you want to return all records use $query->result_array() instead.
Related
how to read multiple value from joined table in codeigniter
this is model.php
public function all_village_info($id = NULL) {
$this->db->select('tbl_village.*', FALSE);
$this->db->select('tbl_school.*', FALSE);
$this->db->from('tbl_village');
$this->db->join('tbl_school', 'tbl_school.school_id=tbl_village.school_id', 'left');
if (!empty($id)) {
$this->db->where('tbl_village.village_id', $id);
$query_result = $this->db->get();
$result = $query_result->row();
} else {
$query_result = $this->db->get();
$result = $query_result->result();
}
return $result;
}
and this is view.php
<table class="table table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th class="col-sm-1" >VILLAGE</th>
<th class="col-sm-1" >ZONE</th>
<th class="col-sm-1" >SCHOOL</th>
</tr>
</thead>
<tbody>
<?php if (!empty($all_village_info)):
foreach ($all_village_info as $v_village) :
?>
<tr>
<td><?php echo $v_village->village_name ?></td>
<td><?php echo $v_village->zone_name ?></td>
<td><?php echo $v_village->school_name ?></td>
</tr>
<?php
endforeach;
?>
<?php endif; ?>
</tbody>
</table>
value in sql_is like
|-------------|------------|
|village_name |school_id |
|-------------|------------|
|Bhiwani |1,2,3 |
view is as
|-------------|------------|
|Village |School |
|-------------|------------|
|Bhiwani |School 1 |
i want to show like
|-------------|-------------------------------|
|Village |School |
|-------------|-------------------------------|
|Bhiwani |School 1, School 2, School 3 |
how can i do that ? help plz
how to read multiple value from joined table in codeigniter
You can use alias of the table and then select those
NOTE : I highly recommend you to use * if and only if your using all the columns else it will make your query bit slower.
/* You can take an alias for the table and select * from that, I have followed chaining method. */
$this->db
->select('v.*, s.*')
->from('tbl_village v')
->join('tbl_school s', 's.school_id = v.school_id', 'left')
->get()
->result_array();
You can try this solution for your problem :
Please change your modal function :
all_village_info:
public function all_village_info($id = NULL) {
$this->db->select('tbl_village.*', FALSE);
$this->db->select('GROUP_CONCAT(tbl_school.school_name ORDER BY tbl_school.school_id) as school_name', FALSE);
$this->db->from('tbl_village');
$this->db->join('tbl_school', 'FIND_IN_SET(tbl_school.school_id, tbl_village.school_id) > 0', 'left');
if (!empty($id)) {
$this->db->where('tbl_village.village_id', $id);
$query_result = $this->db->get();
$result = $query_result->row();
} else {
$query_result = $this->db->get();
$result = $query_result->result();
}
return $result;
}
I hope it will help you.
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();
}
Im fetching data from a table to another table that will be shown in my dashboard page for a user after loggin in.
But there is a problem with the indexes, i got this error:
Here is the line error:
Here is my code:
My view file ("usuario"):
<thead>
<th>id</th>
<th>User</th>
<th>Subject</th>
<th>Grade</th>
<th>Date</th>
</thead>
<tbody>
<?php
if (count($records) > 0 && $records != false) {
foreach($records as $record) {
echo "<tr>
<td>".$record['id']."</td>
<td>".$record['User']."</td>
<td>".$record['name']."</td>
<td>".$record['grade']."</td>
<td>".$record['date']."</td>
</tr>";
}
}
?>
</tbody>
</body>
</html>
My controller file ("login"):
public function home(){
$data['record']=$this->m_login->getDetails();
$this->load->view('usuario',$data);
}
My model file ("m_login"):
public function getDetails()
{
$st=$this->db->SELECT('cursadas.*, usuarios.name as usuarios, materias.name as materias_name')->from('cursadas')
->join('usuarios','usuarios.id=cursadas.user_id')
->join('materias','materias.id=cursadas.subject_id')
->WHERE('cursadas.user_id=',$this->session->userdata['id'])
->get()->result_array();
return $st[0];
}
You have the variable $records on view but not on controller
Change
$data['record'] = $this->m_login->getDetails();
To
// add this array() just in case no results found
$data['records'] = array();
$data['records'] = $this->m_login->getDetails();
$this->load->view('usuario', $data);
Another way is on controller
$results = $this->m_login->getDetails();
$data['records'] = array();
if ($results) {
foreach ($results as $result) {
$data['records'][] = array(
'id' => $result['id'],
'User' => $result['User'],
'name' => $result['name'],
'grade' => $result['grade'],
'date' => $result['date']
);
}
}
$this->load->view('usuario',$data);
View
<?php if ($records) {?>
<?php foreach($records as $record) {?>
<tr>
<td><?php echo $record['id'];?></td>
<td><?php echo $record['User'];?></td>
<td><?php echo $record['name'];?></td>
<td><?php echo $record['grade'];?></td>
<td><?php echo $record['date'];?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>No Results Found</td>
</tr>
<?php } ?>
Wrong array index in your controller.
Change this
$data['record']=$this->m_login->getDetails();
to
$data['records']=$this->m_login->getDetails();
result_array() return returns result with array so you need to it like this -
if (count($record) > 0 && $record != false) {
foreach($record as $rec){
echo "<tr>
<td>".$rec['id']."</td>
<td>".$rec['User']."</td>
<td>".$rec['name']."</td>
<td>".$rec['grade']."</td>
<td>".$rec['date']."</td>
</tr>";
}
}
Please check this from above code and comment if you have any problem
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.
So, i've been using codeigniter for a while and I've never had an issue running a query in my model and returning it to my controller which then passes it into my view where I access it as an object, like so:
MODEL (somemodel)
function getdata()
{
$query = $this->db->get('sometable');
return $query;
}
CONTROLLER (somecontroller)
function controldata()
{
$this->load->model('somemodel');
$data['dbdata'] = $this->somemodel->getdata();
$this->load->view('someview',$data);
}
VIEW (someview)
<?php
foreach($dbdata->result() as $row) {
echo $row->id;
echo $row->name;
echo $row->whatever;
echo "<br />";
}
?>
But now for whatever reason in 2.0 it's making use $dbdata->result_array() as $row instead.
Basically it's returning the results as an array instead.
It doesn't make any sense, has something changed in the new version?
Thanks,
So here's my code:
MODEL (admin_model)
function show_allproducts($sort,$order,$limit,$offset)
{
$this->db->select('products.id,productcategories.categoryname,products.name,products.internetspecial,products.added,products.modified');
$this->db->from('products');
$this->db->join('productcategories','products.productcategories_id = productcategories.id');
$this->db->order_by($sort,$order);
$this->db->limit($limit,$offset);
$query = $this->db->get();
if($query->num_rows() > 0)
{
return $query;
}
else
{
return FALSE;
}
}
CONTROLLER (admin)
function show_allproducts()
{
$data['title'] = 'All Products';
$this->load->library('pagination');
$config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/admin/show_allproducts';
$config['total_rows'] = $this->db->get('products')->num_rows();
$config['per_page'] = 10;
$config['num_links'] = 5;
$config['full_tag_open'] = '<div class="paggination right">';
$config['full_tag_close'] = '</div>';
$config['prev_link'] = '< prev';
$config['next_link'] = 'next >';
$config['cur_tag_open'] = '<a class="active">';
$config['cur_tag_close'] = '</a>';
$this->pagination->initialize($config);
$this->load->model('admin_model');
$data['tabledata'] = $this->admin_model->show_allproducts('name','ASC',$config['per_page'],$this->uri->segment(3));
$data['nav'] = 'admin/pagesections/nav';
$data['maincontent'] = 'admin/pages/show_allproducts';
$this->load->view('admin/template',$data);
}
VIEW (show_all_products)
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<?php if($tabledata) { ?>
<tr>
<th>ID</th>
<th>CATEGORY</th>
<th>NAME</th>
<th>ADDED</th>
</tr>
<?php foreach($tabledata->result() as $row) { ?>
<tr>
<td><?php echo $row->id; ?></td>
<td><?php echo $row->categoryname; ?></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->added;) ?></td>
</tr>
<?php } ?>
<?php } else { ?>
<tr>
<td>NO DATA</td>
</tr>
<?php } ?>
</table>
Unless you specify $dbdata->result_array() as $row , It wont return the results as array. The same code which you've posted must be working in CI 2.0.
If not, may be the problem with $this->db->get('sometable').
Try with $this->db->query('select * from sometable'). But as far as i know, both are same...
Ok folks, no lie, I found the freaking problem.
Looking at the fourth td where $row->added; is at, there's a close parantheses at the end of it that was causing 4 days of mayhem.
Kindest regards to all those who tried to help. Sometimes it doesn't matter how many eyes are on it I guess.