I have a class in Codeigniter which extends CI_Model.
I have declared a global array $data, but I can't access this array from my functions which i want to push some items.
that shows
A PHP Error was encountered Message: Undefined variable: data
and Fatal error: Cannot access empty property in /api/system/core/Model.php on line 51
code for class:
class Subscription_collection_model extends CI_Model {
public $data=array();
/*
|-----------------------------------------
| Constructor
|-----------------------------------------
*/
function __construct() {
parent::__construct();
}
function get() {
$this->db->select('family.house_name,family.id,family_grade.amount');
$this->db->from('family');
$this->db->join('family_grade','family_grade.id = family.family_grade_id');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$this->findBalance($row->id);
}
}
return $data;
}
function findBalance($id) {
$this->db->where('family_id', $id);
$this->db->select_sum('collecting_amount');
$query = $this->db->get('subscription_collection');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
array_push($this->$data,$row->collecting_amount);
}
}
}
}
you got a typo there. you want to call $this->data not $this->$data.
the latter would assume, you wanna call a dynamic variable on the instance.
$prop = 'myProperty';
$this->$prop = 'test';
is the same as
$this->myProperty = 'test';
How about:
return $this->data;
Related
I am trying do display information from my database using codeigniter, but I keep reeving an error message. The error messages is Severity: Warning Message: Invalid argument supplied for foreach().
This is my model:
class stuffModel extends CI_Model {
private $stuff_table = 'Stuff';
function __construct()
{
parent::__construct();
$this->load->database();
}
public function getItem()
{
$un = array();
$res = $this->db->get($this->stuff_table);
$results = $res->result();
return $results;
}
}
And this is my Controller:
public function displayStuff() {
$STUFF= $this->stuffModel->getItem();
$this->load->view('myView',array('stuff' => $STUFF));
}
And this is my View:
<?php
foreach ($stuff as $s) {
echo"<h1>".$s['Items']."</h1>";
}?>
And the error message is Severity: Notice Message: Undefined variable: stuff and Severity: Warning Message: Invalid argument supplied for foreach()
Nothing is jumping out at me and it looks like it should work. Here's a little trouble shooting idea.
Change the controller as follows
public function displayStuff()
{
$data['stuff'] = $this->stuffModel->getItem();
var_dump($data); //share this output here
$this->load->view('myView', $data);
}
You did not load the model into controller that's why you can't call the model from the controller .
first load the model into controller
$this-load->model('modelName');
than call
$this->modelName->methodName();
Changes in Controller
Make sure that the object of model class is declared in the constructor as given below
$this->load->model('stuffModel', 'stuffModel', TRUE);
then in the displayStuff function,
public function displayStuff() {
$data['stuff']= $this->stuffModel->getItem();
$this->load->view('myView',$data);
}
Change in the model
public function getItem()
{
$res = $this->db->get($this->stuff_table);
if ($res->num_rows() > 0) {
return $res->result_array();
} else {
return array();
}
}
Finally in the view
You can display the values stored in the array by iterating as follows
foreach($stuff as $stf){
echo $stf['field_name'];
}
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
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();
}
I am new to PHP and Codeigniter, and I am declaring a class level variable which I wanted to access in model class. I'm getting an error that the variable is not defined. Here is my code:
class Country_model extends CI_Model{
protected $table = 'COUNTRY';
function __construct()
{ // Call the Model constructor
parent::__construct();
}
function retriveAll(){
$q = $this->db->from($table)
->order_by('ID','ASC')
->get();
if ($q->num_rows()>0){
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
}
I have declared $table and accessing in retriveAll function. Please help me.
That's not how you access class variables. Try using $this->table instead:
function retriveAll(){
$q = $this->db->from($this->table)
->order_by('ID','ASC')
->get();
if ($q->num_rows()>0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
Access your class variable with $this, like:
$this->table