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.
<?php
class User_model extends CI_Model {
public function get_users(){
$data=$this->db->get('users');
return $data->result();
}
}
?>
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
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
Can I obtain the model directly from a query in Code Igniter?
Model
<?php
class User_Model extends CI_Model {
public $user_id;
public $name;
public $team_id
public function getTeamName() {
$this->db->select('name');
$this->db->from('team');
$this->db->where('team_id',$this->team_id);
$query = $this->db->get();
$team = $query->row();
if($empresa == null){
return "";
} else {
return $team->name;
}
}
public function getUser($id) {
$query = $this->db->get_where('users', array('user_id' => $id));
$user = $query->row();
return $user;
}
I would like getUser($id) function returns a user object like 'new User_Model()' to be able to use getTeamName() function in the view. Can I do it?
Now returns an object, but not a User_Model() object.
is wrong call a method in the model from the view.
in the model use
function getUser($id){
$query = $this-db->select('*')
->from('users')
->where('user_id', $id)
->get();
return $query->result();
}
this return a object with all data, then you call the method in the controller like this
$data['user_model'] = $this->model_name->getUser($id);
$this->load->view('Your_View',$data);
then in the view $user_model is the object
in the view
print_r($user_model);
As long as the model is loaded, in your view you can access any public function or property like:
$this->user_model->getUser() or $this->user_model->team_id
View:
<?php
echo $this->user_model->getUser(1)->username;
This is against MVC in some respects but I can understand the logic behind doing so based on the following scenario where you want to say use num_rows and result without doing count:
class User_Model extends CI_Model {
public function getUsers() {
return $this->db->get('users');
}
}
class Some_Controller extends CI_Controller {
public function index() {
$this->load->model('user_model');
$data['users'] = $this->user_model->getUsers();
$this->load->view('some_view', $data);
}
}
View:
<?php
if ($users->num_rows() > 0) {
foreach ($users->result() as $row) {
echo $row->username;
}
} else {
echo 'No users';
}
Actually there is another possibility you can use
create a Team_model and an User_model
The Team_model could look like
class Team_model extends CI_Model
{
$arrTeamNames = [];
public function getTeamName($team_id)
{
if (!isset($this->arrTeamNames[$team_id]))
{
$query = $this->db
->select('name')
->from('team')
->where('team_id',$this->team_id)
->get();
if ($query->num_rows() == 1)
{
$objTeam = $query->row();
$this->arrTeamNames[$team_id] = $objTeam->name;
return $objTeam->name;
}
return '';
}
return $this->arrTeamNames[$team_id];
}
}
and the User_model
class User_Model extends CI_Model
{
public function getUser($id)
{
$query = $this->db->get_where('users', array('user_id' => $id));
if ($query->num_rows() == 1)
{
$user = $query->row(0, 'User_Object');
return $user;
}
}
}
class User_Object
{
public function getTeamName()
{
$ci = get_instance();
$ci->load->model('Team_model');
return $ci->team_model->getTeamName($this->team_id);
}
}
Note in the User_model you have an additional User_Object which
gets mapped by the row() function which is well documented
here.
Now if you call this model in one of your controller and pass it to your view you actually can access to a model function in a proper way e.g.
class User extends CI_Controller
{
public function detail($user_id)
{
$this->load->model('User_model');
$objUser = $this->User_model->getUser($user_id);
$this->load->view('user-detail', ['objUser' => $objUser]);
}
}
//user-detail view
echo $objUser->getTeamName();
I want to get data from the database and display it on a webpage using CodeIgniter. I coded my controller, model and view as follows.
Controller;
//HomeController
<?php
class HomeController extends CI_Controller
{
public function index()
{
$this->load->model('HomeModel');
$data['records'] = $this->HomeModel->getData();
$this->load->view('HomeView',$data);
}
}
?>
Model;
//HomeModel
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$query = $this->db->query('SELECT * FROM data');
return $query->unbuffered_row('object');
}
}
?>
View;
//HomeView
<?php
echo "Recoeds from database<br>";
while($records)
{
echo $records->name." ".$records->age."</br>";
}
?>
But this code doesn't print anything on the screen.(echo "Records from database<br>"; )
So I tried the following code given in the CodeIgniter documentation and echoed the result in the model itself rather than return it to the controller and then to the views.It worked fine.
//HomeModel
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$query = $this->db->query('SELECT * FROM data');
while ($row = $query->unbuffered_row())
{
echo $row->name;
echo $row->age;
}
}
}
?>
My question is how do we return the result of the unbuffered_row() method into the controller and then to the view as per MVC architecture? We can get the output by echoing result at the model itself but it is against the purpose of the MVC architecture.
You should use return $query->result(); and then get the right object in the view or controller (that's up to you).
Try This One
controller
<?php
class HomeController extends CI_Controller
{
public function index()
{
$this->load->model('HomeModel');
$data['records'] = $this->HomeModel->getData();
$this->load->view('HomeView',$data);
}
}
?>
Model
<?php
class HomeModel extends CI_Model
{
public function getData()
{
$data = $this->db->query('SELECT * FROM data');
return array('count'=>$data->num_rows(), 'data'=>$data->result(),'first'=>$data->row());
}
}
?>
View
<?php
echo "Recoeds from database<br>";
foreach($record['data'] as $row)
{
echo $row->name." ".$row->age;
}
?>
I simulated your code in local.Your mistake is here.$records is object .And your while loop has not condition for leaving the loop
<pre>
<?php
var_dump($records);
echo "Recoeds from database<br>";
foreach($records as $value) {
echo $value->name."<br>";
echo $value->age."<br>";
}
?>
</pre>
it's my model code:
<?php
class Books_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function get_restaurants()
{
$sql = "SELECT id, names FROM restaurants ";
$query = $this->db->query( $sql );
return $query->result();
}
}
controller code:
<?php
class Booking_Controller extends CI_Controller
{
public function __construct(){
parent::__construct();
$this->load->model('Books_model');
}
public function view()
{
$this->user_data['result']=$this->Books_model->get_restaurants();
$this->load->helper(array('form','url'));
$this->load->view('restaurants/booking',$this->user_data);
}
}
What code I written in view file that the data show in text field?
Try the following :
In the Controller
class Booking_Controller extends CI_Controller
{
public function __construct(){
parent::__construct();
$this->load->model('Books_model');
}
public function view()
{
$data['results'] = $this->Books_model->get_restaurants();
$this->load->helper(array('form','url'));
$this->load->view('restaurants/booking',$data);
}
}
In the View:
<?php
foreach ($results as $result)
{?>
<label>Restaurant Name : </label>
<input type="text" value="<?php echo $result->names;?>" />
<?php } ?>
in the controller
<?php
class Booking_Controller extends CI_Controller
{
public function __construct(){
parent::__construct();
$this->load->model('Books_model');
}
public function view()
{
$data["result"]=$this->Books_model->get_restaurants();
//$this->load->helper(array('form','url')); not needed
$this->load->view('restaurants/booking',$data["result"]);
}
}
now in your view
<?php
// notice that CI strip the key "result" from the array $data to become a variable $result in the view
foreach ($result as $row)
{
echo $row->id."<br>";
echo $row->name."<br>";
echo "----";
}
?>
Note:
there is no member like this "$this->user_data['result']" in
codeigniter but there is "$this->session->user_data("data_name")" if
you want to store some data in the session, but then, no need to pass
it to the view as an argument you can call the session data from the
view directly
i got this fatal error when i run this on browser please solve my problem...i don't get whats wrong with this code.........Fatal error: Call to a member function where() on a non-object
Fatal error: Call to a member function where() on a non-object
model
<?php
class News extends CI_Model
{
function Users(){
//call model constructor
parent::Model();
//load database
$this->load->database();
}
public function get_all_news(){
$this->db->get('news');
if($query->num_rows()>0){
//return result set as associate array
return $query->result_array();
}
}
public function getnews($field,$param){
$this->db->where($field,$param);
$query=$this->db->get('news');
// return result set as accosiate array
return $query->result_array();
}
public function getnumnews(){
return $this->db->count_all('news');
}
}
?>
controller
<?php
class News_data extends CI_Controller{
public function Users(){
// load controller parent
parent::Controller();
// load ‘Users’ model
}
public function index(){
$this->load->model('News');
$data['users']=$this->News->getnews('id <',5);
$data['numusers']=$this->News->getnumnews();
$data['title']='Displaying user data';
$data['header']='User List';
// load ‘Show_data’ view
$data['title']='Display data';
$this->load->view('Show_data',$data);
}
}
?>
view
</head>
<body>
<h1><?php echo $header;?></h1>
<ul>
<?php foreach($users as $user):?>
<li>
<p><?php echo $user['id'].' '.$user['title'].' '.$user['tetxt'];?></p>
</li>
<?php endforeach;?>
</ul>
<p><?php echo 'Total number of users :'.$numusers;?></p>
</body>
</html>
?>
You may not initialising the db object $this->db here $this->db->where($field,$param); OR your $this->db is null.
Please load the database in the model constructor or load via autoload.php
please modify your model as shown below
class News extends CI_Model
{
function __construct(){
$this->load->database();
}
function Users(){
//call model constructor
parent::Model();
//load database
$this->load->database();
}
public function get_all_news(){
$this->db->get('news');
if($query->num_rows()>0){
//return result set as associate array
return $query->result_array();
}
}
In my controller I went from getting the data right there (which worked fine):
$data['query'] = $this->db->query("MY DB QUERY");
$this->load->view('shopci_view', $data);
to grabbing the data from a class model function:
class Shopci_model extends CI_Controller {
function __construct()
{
parent::__construct(); //model constructor
}
//display sale itmes on shopci_view.php
function sale_items()
{
$query = $this->db->query('MY DB QUERY - SAME AS ABOVE');
return $query->result();
}
}
new controller function:
//load model, auto connect to db
$this->load->model('Shopci_model', '', TRUE);
//Display items for sale
$data['query'] = $this->Shopci_model->sale_items();
$this->load->view('shopci_view', $data);
ERROR:
Fatal error: Call to a member function result() on a non-object in
shopci_view
This is the line in the view that worked before I switched to the model (didn't change view):
<?php foreach($query->result() as $row): ?>
Any help is appreciated.
Thank You.
In your model you return the $query as a result() array to the controller.
So you cannot then use 'foreach $query->result()' again - because you have already done that;
This should work
<?php foreach($query as $row): ?>
OR if you want - just change the model from
return $query->result();
to
return $query;
In your model you want to return the data to pass to the controller. So in your model you would have
function sale_items()
{
$query = $this->db->query(SAME AS OLD);
return $query;
}
and then your controller will be the same and your foreach in your view should be the following
<?php foreach ($query as $row): ?>