Codeigniter: Call to a member function result_array() on a non-object - php

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();
}

Related

Invalid arguments in foreach() function

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

Invalid argument supplied Codeigniter

My program is not working properly, i do not know what should i do :S
I got this error message:
Take a look at this:
Here is my code:
My controller file (Home):
<?php
class Home extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Crudmodel");
}
public function index(){
# get all data in Study table
$selectStudys = $this->Crudmodel->selectStudys();
foreach ($selectStudys as $key => $study)
{
# get UserNames
$user = $this->Crudmodel->getName($study['user_id']);
#get Subject Names
$subject = $this->Crudmodel->getSubName($study['subject_id']);
#append both NEW VALUES to same array
if(!empty($user[0]['username'])){
$data[$key]['user_id'] = $user[0]['username'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]['user_id'] = ''; // or anything as your else condition you can use as error handler
}
if(!empty($subject[0]['name'])){
$data[$key]['subject_id'] = $subject[0]['name'];
// your main problem can be this. may be it is not getting value from query this is why we have put validation on model function and error handler condition here
}else{
$data[$key]["subject_id"] = "";
// or anything you can use as error handler
}
}
$data['records'] = $selectStudys;
$this->load->view('home', $data);
}
}
?>
Crudmodel:
class Crudmodel extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
function getName($name)
{
$query= $this->db->query("SELECT username FROM usuarios WHERE id = $name ");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = "";
// or anything you can use as error handler
return $result;
}
}
Dont know what to do now :(
Hope you can help me :S
The problem is in the model. You only return something inside the else. Easy fix, move the return.
You should probably return an empty array if there are no rows. Then the foreach will still have something to work with - even if it is empty. foreach will choke if given something that cannot be used in a loop - a string for instance.
function selectStudys()
{
$query= $this->db->query("SELECT * FROM cursadas");
if($query->num_rows()>0){
$result = $query->result_array();
}else{
$result = array();
}
return $result;
}

Cannot use object of type QueryResult as array, Using Salesforce library with CI

I got an error
"Cannot use object of type QueryResult as array"
I am simply trying to take state name from the records array but, I only manage to get this error "Cannot use object of type QueryResult as array"
Model.php
public function getstatename()
{
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
return $statename;
}
Controller.php
public function index() {
$data['getstatename'] = $this->model->getstatename();
$this->load->view('footer', $data);
echo "<pre>";
print_r($data['getstatename']['records']);
}
Actually $statename is result-set object not an array.
So you need to do like below:-
Model.php:-
public function getstatename(){
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
$state_array = array(); // create an array
foreach ($statename as $row){
$state_array[] = $row->State__c; // assign value to array
}
return $state_array; // return array
}
Controller.php:-
public function index() {
$data['getstatename'] = $this->Footer_model->getstatename();
echo "<pre/>";print_r($data['getstatename']); // check this and accordingly change you code further
$this->load->view('footer', $data);
}
Here is the solved code Thanks to #Anant
Model.php
public function getstatename()
{
$statename = $this->salesforce->query ("SELECT State__c FROM RI_School_List__c group by State__c");
$state_array = array();
foreach ($statename as $row){
$state_array[] = $row->State__c;
}
return $state_array;
}
Controller.php
public function index() {
$data['getstatename'] = $this->Footer_model->getstatename();
$this->load->view('footer', $data);
}
See if you can do
$data['getstatename']->fetchRow();

Fatal error: Call to a member function result() on a non-object in Codeigniter

Fatal error: Call to a member function result() on a non-object in D:\wamp\www\ocss\application\core\My_Model.php on line 111
class Report extends MY_Controller{
public function item_ladger()
{
$material = $this->Material_Model->get(); // when i call it here it works fine
$inventory = $this->db->query("CALL inventory($id)")->result_array();
$material = $this->Material_Model->get(); // when i call it here it Generate Fatal error: Call to a member function result() on a non-object in
}
}
what's the reason behind?
EDIT
this is my material model it has table name and all table fields
class Material_Model extends MY_Model
{
const DB_TABLE = 'material';
const DB_TABLE_PK = 'material_id';
public $material_id;
public $material_name;
public $size;
public $rate;
}
this is my MY_Model it has table name and get method to get all result
class MY_Model extends CI_Model {
const DB_TABLE = 'abstract';
const DB_TABLE_PK = 'abstract';
public function get($limit = 500, $offset = 0,$desc=true) {
if ($limit) {
if ($desc)
$query = $this->db->order_by($this::DB_TABLE_PK, 'DESC')->get($this::DB_TABLE, $limit, $offset);
else
$query = $this->db->get($this::DB_TABLE, $limit, $offset);
}
else {
$query = $this->db->get($this::DB_TABLE);
}
$ret_val = array();
$class = get_class($this);
foreach ($query->result() as $row) {
$model = new $class;
$model->populate($row);
$ret_val[$row->{$this::DB_TABLE_PK}] = $model;
}
return $ret_val;
}
Finally i have solved my problem by simply calling mysql query instead store procedure
class Report extends MY_Controller{
public function item_ladger()
{
$material = $this->Material_Model->get(); // when i call it here it works fine
$inventory = $this->db->query("My Query To Database")->result_array();
$material = $this->Material_Model->get(); // now when i call it here there is no error
}
}
but i am confused my that error acure when calling store procedure instead query
class Report extends MY_Controller{
public function item_ladger()
{
$this->load->model("Material_Model"); # loding Model
$inventory = $this->Material_Model->get_data(); # caling Model to do my code
if ($inventory['cup']) { # retrivig data from retund array
echo "I never ate Cup Cakes";
}
}
}
In Model
public function get_data()
{
$query = $this->db->get('cake'); # get data from table
$result = $query->result_array(); # re-Assign as objective array
return $result; # return data
}
Codeigniter SELECT

call a function where there is existing on the table

I use codeigniter mvc for my project, im making a unique id logger that if there id exist it will call the unique generator function again. how to call the function inside model
heres my model:
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
// call function again
} else {
// if not exist save!!
}
}
you can call $this->getGenLogsId();
function getGenLogsId() {
$matches = '12345';
$sql = "SELECT * FROM tbllogs WHERE logsid LIKE '%".$this->db->escape_like_str($matches)."%'";
$q = $this->db->query($sql);
if($q->num_rows() > 0) {
$this->getGenLogsId();
} else {
// if not exist save!!
}
}
if it's in the same controller use :
$this->function();
if it's in the model:
$this->load->model('ModelName');
$this->ModelName->function();
NOTE
if it's in the controller it's a good practice to make it a private function so no direct call is allowed to that function by starting the function name with _
Example:
function _test(){
}

Categories