Home > Back-end >  Invalid argument supplied for foreach() - Codeignitor
Invalid argument supplied for foreach() - Codeignitor

Time:11-25

I am getting an error "Invalid argument supplied for foreach()" while trying to fetch 'id' column using foreach loop: Codeignitor version: 3.0.1

Controller:

<?php

class Users extends CI_Controller {
    
    public function show(){
        
        $this->load->model('user_model');
        $result = $this->user_model->get_users();
        foreach($result as $object){
            echo $object->id;
         }
    }
}

?>

Model:

<?php

class User_model extends CI_Model {
    
    public function get_users(){
    $this->db->get('users');
    }
}


?>

As I checked table name and column names are correct.

CodePudding user response:

<?php

class User_model extends CI_Model {
    
    public function get_users(){
    $data=$this->db->get('users');
    return $data->result();
    }
}


?>

CodePudding user response:

you can fetch by using either result() or result_array() in model

in your case

public function get_users(){ // model
    $data=$this->db->get('users');
    return $data->result();
}

public function show(){ // controller
    
    $this->load->model('user_model');
    $result = $this->user_model->get_users();
    foreach($result as $object){
        echo $object->id;
     }
}

The above method returns the query result as an array of objects, or an empty array on failure.

The below one method returns the query result as a pure array, or an empty array when no result is produced.

you can also do this

public function get_users(){ // model
    $data=$this->db->get('users');
    return $data->result_array();
}

public function show(){ // controller
    
    $this->load->model('user_model');
    $result = $this->user_model->get_users();
    foreach($result as $object){
        echo $object['id'];
     }
}

for more details click here

CodePudding user response:

you need to return result() or result_array()

<?php
  class User_model extends CI_Model {
    public function get_users(){
    $data=$this->db->get('users');
    return $data->result(); // or  return $data->result_array();
    }
   }
?>

for result arrray you need to echo $object['id']; and for result() same as you printing.

  • Related