简体   繁体   中英

Codeigniter - displaying data based on if condition

This is the controller:

 function list_requests(){
    $data['requests'] = $this->mdl_request->show_requests();
$data['main_content'] = 'backend/requests/requests';
        $data['title'] = 'Requests';
        $this->load->view('includes/template', $data);
    }

This is my model:

function show_requests()
    {

        $this->db->order_by('created_time','asc');
        $this->db->group_by('orderid');
        $this->db->from('requests', 'items');
        $this->db->join('items', 'items.item_id = requests.item_id');
        if($user_id != '')
            $this->db->where('created_by', $user_id);
        $query = $this->db->get();
        return $query->result();
    }

I have tried this in view

<?php 
  if($request->is_approved == yes){ 
   foreach($requests as $request):
     echo $request->request_name;
     endforeach;
   }
?>

this is the error showed

A PHP Error was encountered Severity: Notice Message:
Undefined variable: request Filename: requests/requests.php
Line Number: 128
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: requests/requests.php
Line Number: 128

So, how can I display only approved requests? and I need to handle it in view, not in the model.

Try this

<?php 

   foreach($requests as $request) {
     if($request->is_approved == yes) { 
       echo $request->request_name;
     }
   }    

?>

Try this - with testing shown. This is assuming that your use of testing against yes is meant to be the string value of 'yes'.

<?php
// Dummy Data for testing
$requests = array(
    (object)(array('is_approved'=>'yes','request_name'=>'Fred')),
    (object)(array('is_approved'=>'no','request_name'=>'Sam')),
    );

// Does it look right?
var_dump($requests);

// The Code to test.
foreach($requests as $request) {
    if($request->is_approved == 'yes') {
        echo $request->request_name;
    }
}

Output of the above is

array (size=2)
  0 => 
    object(stdClass)[1]
      public 'is_approved' => string 'yes' (length=3)
      public 'request_name' => string 'Fred' (length=4)
  1 => 
    object(stdClass)[2]
      public 'is_approved' => string 'no' (length=2)
      public 'request_name' => string 'Sam' (length=3)
Fred

This Line...

if($request->is_approved == yes)

Is attempting to compare $request->is_approved against a constant called yes.

If you haven't defined yes as a constant with a value of 'yes', then bassed upon the field name "is_approved" being a varchar/string, you need to test it against the string 'yes' like so...

if($request->is_approved == 'yes')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM