This is the error which i am getting
I am trying to fetch an array in codeignitor but it is giving me this error:
<?php
foreach($name as $object)
{
echo $object->name . '<br/>';
}
?>
And my Controller code is
public function index()
{
$this->home();
}
public function home()
{
$this->load->model('model_users');
$data['title'] ='First MVC tutorial';
$data['page_header'] ='Intro to MVC';
$data['name'] = $this->model_users->getNames();
$data['users'] = $this->model_users->getUsers();
$this->load->view('welcome_message',$data);
}
This is the model
class Model_users extends CI_Model {
function _construct()
{
parent::_construct();
}
function getNames()
{
$query = $this->db->query('SELECT name from users');
if($query->num_rows>0){
return $query ->result();
}
else{
return NULL;
}
}
function getUsers()
{
$query = $this->db->query('SELECT * from users');
if($query->num_rows>0){
return $query->result();
}
else{
return NULL;
}
}
So can anyone help me solve this error??
As i am new to new to codeignitor
Thanks in advance.
This is the screenshot of my table
Do you have any rows in your users table?
It seems that your model returns null, and foreach expects an Array as it's array_expression var. Could be an empty array as well.
So you might wan't to change the
return NULL;
to
return [];
in your model and that should at least prevent the error.
p.s.
http://php.net/manual/en/control-structures.foreach.php
Related
Customers_model
Class Customers_model extends BF_Model{
protected $table_name = 'customers';
protected $key = 'customer_id';
protected $date_format = 'datetime';
My query function in model
function get_customerlist()
{
$sql = $this->db->query('SELECT first_name, last_name , customer_id FROM customers ');
return $sql->result();
}
}`
Controller
public function listCustomer()
{
$this->load->model('customers_model'); // whatever you call it
$data['list'] = $this->customers_model->get_customerlist();
$this->load->view('myview', $data);
}
View
foreach($list as $value)
{
echo $value->first_name. '<br />'; output.
}
It can't show $list array from controller : Undefined list variable
In your Model Query method i made few changes,
function get_customerlist()
{
$selelct = array('first_name','last_name','customer_id');
return $this->db->select($select)
->from('customers')
->get()
->result();
}
In your Controller,
public function listCustomer()
{
$this->load->model('customers_model'); // whatever you call it
$list = $this->customers_model->get_customerlist();
$data['list'] = $list; //returned result is an array of object
$this->load->view('myview', $data);
}
In Your view,try this,
foreach((array)$list as $item)
{
echo $item->first_name. '<br />';
}
It should work.
i'm trying to learn codeigniter and i have problem here. There was an error Undefined variable and Invalid argument supplied for foreach() on view. here is the code :
Model (Model_Users.php) :
class Model_users extends CI_Model {
function __construct() {
parent::__construct();
}
function getFirstNames(){
$query = $this->db->query('SELECT firstname FROM users');
if($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getUsers(){
$query = $this->db->query('SELECT * FROM users');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
}
Controller (welcome.php) :
class Welcome extends CI_Controller {
public function index()
{
$this->home();
}
public function home()
{
$this->load->model('model_users');
$data['title'] = 'MVC Cool Title';
$data['page_header']='Intro to MVC Design';
$data['firstnames'] = $this->model_users->getFirstNames();
$data['users'] = $this->model_users->getUsers();
$this->load->view('welcome_message',$data);
}
}
View (Welcome_message.php) :
<div id="container">
<h1><?php echo $page_header ?></h1>
<div id="body">
<?php
foreach ($firstnames as $object) {
echo $object->firstname .'<br/>';
}
echo '<br/><hr/><br/>';
foreach ($users as $object){
echo $object->firstname . '\'s email address is'. $object->email . '<br/>';
}
?>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
Please help me what is wrong with my code ?
First check value return any value or not write this code in controller
use
var_dump($firstnames);
and
var_dump($users);
I think no data return from model
check any data in table
Thanks
You can eliminate the error by using return []; instead of return null; instead of checking for that case in every foreach call, because it appears that your user table might be empty based on the code provided.
Modify your model functions like below
function getFirstNames(){
$query = $this->db->get('users')->row()->firstname;
if($query->num_rows() > 0) {
return $query->result_array();
} else {
return NULL;
}
}
function getUsers(){
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return NULL;
}
}
hope this will help
I have two functions in my model as
class Jobseeker_model extends CI_Model
{
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function result_getall($id)
{
$this->db->select('*');
$this->db->from('tbl_jobseeker');
$this->db->where('tbl_jobseeker.User_id',$id);
$this->db->join('tbl_work_exp', 'tbl_jobseeker.User_id = tbl_work_exp.User_id','left');
$query = $this->db->get();
return $query->row();
}
public function select($id)
{
$this->db->select('*');
$this->db->from('tbl_qualification');
$this->db->where('tbl_qualification.User_id',$id);
$query = $this->db->get();
return $query->result();
}
}
And in my controller I have a function as
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$res['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data,$res);
}
It is not possible to display the view page.. I could pass two variables into my view page.right?
You can pass your any number of variables/arrays using a single array.
In Controller:
public function display() {
$id = $this->session->userdata('user_id');
$data['var1'] = $this->jobseeker_model->result_getall($id);
$data['var2'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
In View:
`$var1` and `$var2` will be available.
You can pass your two variable using single srray
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
Views
foreach($a as $data){
// your code
}
echo $row->column_name;
Try this
public function display()
{
$id = $this->session->userdata('user_id');
$data['row'] = $this->jobseeker_model->result_getall($id);
$data['a'] = $this->jobseeker_model->select($id);
$this->load->view('jobseeker_display.php', $data);
}
I'm trying to write some classes which pull my data out of my database and create objects based on that data. I'm working with CodeIgniter.
The problem is that if an id is supplied to the __construct method but no row in the database table has that id, an object is returned but with all the properties set to NULL.
Is there a way that I can check this and return NULL instead of an object if there is no corresponding row?
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
...
public function __construct($id = NULL){
if($id){
$this->getFromDatabase($id);
}
}
...
function getFromDatabase($id){
foreach($this->database_keys as $key){
$this->db->select($key);
}
$this->db->from($this->database_table_name);
$this->db->where('id', $id);
$this->db->limit(1);
$q = $this->db->get();
if ($q->num_rows() > 0){
foreach($q->result() as $property){
foreach($property as $key => $value){
$this->$key = $value;
}
}
} else {
// NEED TO SET THE OBJECT TO NULL FOR THIS CASE
}
}
...
}
Any help would be appreciated.
This is not possible, once __construct is called, you will receive an object instance.
The correct way to handle this is to throw an Exception from inside the constructor.
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
public function __construct($id = NULL){
if($id){
$row = $this->getFromDatabase($id);
if (!$row) {
throw new Exception('requested row not found');
}
}
}
}
try {
$record = new JS_Model(1);
} catch (Exception $e) {
echo "record could not be found";
}
// from here on out, we can safely assume $record holds a valid record
why dont you make your constructor private and use a method such as GetInstance(); something like this. Syntax may be incorrect as i dont write much php anymore :-(.
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
...
private function __construct($id = NULL){
}
public static function GetInstance($id)
{
$x = new JS_Model($id);
$x->getFromDatabase($id);
if(is_object($x))
{
return $x;
}
return null;
}
...
function getFromDatabase($id){
foreach($this->database_keys as $key){
$this->db->select($key);
}
$this->db->from($this->database_table_name);
$this->db->where('id', $id);
$this->db->limit(1);
$q = $this->db->get();
if ($q->num_rows() > 0){
foreach($q->result() as $property){
foreach($property as $key => $value){
$this->$key = $value;
}
}
} else {
return null;
}
}
...
}
I'm using Codeigniter to build a webapp and I received this error:
Fatal error: Call to a member function result_array() on a
non-object in /var/www/application/controllers/people.php on line 29
This is the people.php class:
public function __construct()
{
parent::__construct();
}
function People() {
}
function view($id) {
echo "Hello world " . $id;
}
function all() {
$this->load->model('people_model', '', TRUE);
$allContacts = $this->people_model->get_all_contacts();
$results = array();
foreach ($allContacts->result_array() as $row) {
$eachrow = array("personID"=>$row['personID'],"fName"=>$row['fName'],"lName"=>$row['lName'],"phoneNumber"=>"",
"emailAddress"=>$row['emailAddress'],"address"=>$row['address'],"city"=>$row['city'],"state"=>$row['state'],"zip"=>$row['zip']);
$results = push_array($results, $eachrow);
}
foreach ($results as $row) {
$phoneData = $this->people_model->get_phone_by_id($row['personID']);
$phoneNumbers = "";
foreach ($phoneData->result_array() as $row2) {
$phoneNumbers = $row2['type'] . " " . $row2['phoneNumber'] . " " . $row2['extension'];
}
$results['phoneNumber'] = $phoneNumbers;
}
$data['title']="Page Title Goes Here";
$data['username']="Your Username";
$this->load->view('header', $data);
$this->load->view('people_results', $results);
$this->load->view('footer');
}
}
Here is the people_model class:
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_all_contacts() {
$query = $this->db->query('SELECT * FROM person');
return $query->result();
}
function get_phone_by_id($id) {
$query = $this->db->query('SELECT * FROM phoneNumber WHERE personID = '.$id);
return $query->result();
}
}
The only thing I might question in database.php is if the hostname needs a port number, but I don't think that helped when I tried it.
I just tried adding (based on similar question in side bar)
$this->mydb = $this->load->database('realDB', TRUE);
to the people_model and changing the db to mydb and received this error:
You have specified an invalid database connection group.
and this is my line in database.php:
$db['default']['database'] = 'realDB';
Thanks for all your help.
since get_all_contacts is already using the result() function in your model, you can't also use the result_array() function in your controller. result_array() would be a method of the $query object. The quick and dirty way to get this working(which might break other stuff if its also using the get_all_contacts method) would be to change your get all contacts function to the following:
function get_all_contacts() {
$query = $this->db->query('SELECT * FROM person');
return $query;
}
however, if you want to be smarter about it and not risk breaking other stuff, you can pass a param from the controller, and only return query if its set like so:
REVISED CONTROLLER LINE**
$allContacts = $this->people_model->get_all_contacts(true);
REVISED MODEL CODE
function get_all_contacts($special = false) {
$query = $this->db->query('SELECT * FROM person');
if($special)
{
return $query;
}
return $query->result();
}