• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Codeigniter - get only 1 row from table

#1
I know this is a noob question but atm I can't figure out what i'm doing wrong.

I have model :
PHP Code:
public function getRow($id$table)    {
$data NULL;

$this->db->select()
->
from($table)
->
where('id'$id)
->
where_not_in('deleted''1');

$query $this->db->get();
if (
$query->num_rows() > 0)    {
 
  return $query->row(); 
}

return 
NULL;


and in view :

PHP Code:
<?php echo $data->column_name?>

This work but if there are no records I get :   Trying to get property of non-object ..

I can't for the life of me remember how I fix the problem last time ...
Reply

#2
filter $data to check if it is NULL (No Records) before displaying it
Reply

#3
In your controller add code like this
PHP Code:
public function view($id)
{
    
$data['row_item'] = $this->your_model->getRow('id''table');

    if (empty(
$data['row_item']))
    {
        
show_404();
    }

    
$this->load->view('templates/header'$data);
    
$this->load->view('view'$data);
    
$this->load->view('templates/footer');

Reply

#4
(03-20-2015, 03:07 AM)suhindra Wrote: In your controller add code like this

PHP Code:
public function view($id)
{
    
$data['row_item'] = $this->your_model->getRow('id''table');

    if (empty(
$data['row_item']))
    {
        
show_404();
    }

    
$this->load->view('templates/header'$data);
    
$this->load->view('view'$data);
    
$this->load->view('templates/footer');



That can't help at all .. Since i don't want to display a error page. I need to get records from a row and display then ( ' works' ) and if the return is NULL to display "nothing" at the section where I wanted to display them .. not to give error ...
Reply

#5
(03-20-2015, 03:13 AM)GrigoreMihai Wrote: That can't help at all .. Since i don't want to display a error page. I need to get records from a row and display then ( ' works' ) and if the return is NULL to display "nothing" at the section where I wanted to display them .. not to give error ...

How about add if(isset()) in your view?
PHP Code:
<?php 
if(isset($datas)){
 
   foreach ($datas as $data){ 
 
   echo $data->column_name;
 
   }
} else {
 
   echo "nothing";
}
?>
Reply

#6
Since you return NULL if none are found, then in your view you'd need to test for that and display a message or something.

PHP Code:
<?php if (is_null($data)): ?>
<p>Sorry, no records found</p>
<?php else: ?>
<div><?php echo $data->column_name?></div>
<?php endif; ?>
Reply

#7
Thanks .... works perfect ... forgot about is_null and isset ....
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.