how to get num_rows() on a non-object in CI - php

so i'd like to get the response from my model:
function get_list_sales_kit(){
$brispot = $this->load->database('brispot',TRUE);
$brispot->select('id,title,imgurl,description');
$qrydata = $brispot->get('saleskit');
$brispot->close();
return $qrydata->result();
}
and this is the function to call that model:
function salesKit2($request){
$result = new stdClass;
$user='';
$CI =& get_instance();
$CI->load->library('libs_bearer');
$CI->load->library('libs_brispot');
$CI->load->model('service_model');
$datapost = json_decode($request);
if(isset($datapost->user)){
$user = substr('00000000'.$CI->security->xss_clean(trim($datapost->user)),-8);
if($CI->libs_bearer->cekToken($user)==true){
$getdata = $CI->service_model->get_list_sales_kit();
if($getdata->num_rows()>0){
$result->responseCode='00';
$result->responseDesc='Inquiry berhasil.';
$result->responseData=$getdata->result();
}
}
but i got eror result like fatal eror Call to a member function num_rows() on a non-object.
i confused how to call non object on num_row, or is there anything to replace num_row to get the response?

If you really want to return the result from your get_list_sales_kit() function the only way to get the number of rows is to count($getdata) as Lawrence said in the comments.
With that being said, I sometimes return the database object itself like so:
function get_list_sales_kit(){
$brispot = $this->load->database('brispot',TRUE);
$brispot->select('id,title,imgurl,description');
$qrydata = $brispot->get('saleskit');
$brispot->close();
return $qrydata; // this line changed
}
as such you can run any CI database functions on it like row() result() num_rows() and so on. Nothing has to be changed in the second code snippet as for some reason you are already accessing the result() object even though you are returning it in the first function.
Note: I'm not sure if close() will affect the objects being called after the fact. Why are you closing the database after doing one thing?

Related

Pass variable from controller to view

In my controller, I can get the organization name but when I pass it to the view
there's an error. It said invalid argument supplied for foreach( ):
.
This is my codes.
Controller
public function index()
{
$user_id = $this->session->userdata('user_id');
$data['title'] = "User";
$getID['orgID'] = $this->userModel->getOrganizationID($user_id); // used my session user_id to
foreach ($getID['orgID'] as $orgID)
{
$org_id = $orgID->org_id;
$getName['myOrganization'] = $this->userModel->myOrganization($org_id);
foreach($getName['myOrganization'] as $orgName)
{
$name = $orgName->org_name;
$data['name'] = $name;
}
}
$this->load->view('xxxx/xxxx/xxxx',$data);
Model
public function getOrganizationID($user_id)
{
$this->db->select('org_id');
$this->db->from('organization_members');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query->result();
}
public function myOrganization($org_id)
{
$this->db->select('org_name');
$this->db->from('tblorganization');
$this->db->where('org_id', $org_id);
$query = $this->db->get();
return $query->result();
}
My output
First array is my result of $getID['orgID'] = $this->userModel->getOrganizationID($user_id); which I used my user_id session to get all the org_id of the user then
Second array is my result of $getName['myOrganization'] = $this->userModel->myOrganization($org_id); which I used my org_id(from my previous method) to get all the org_name of the user.
Is there going to be more then one result? Because if its only one result then you can use $query->row(); and eliminate the foreach completely.
Always check to make sure your database method worked AND that you actually got a returned value whenever you are making any database call. So i'll let you add the if condition in the database method but in short it should return FALSE if nothing came back. So thats the database method heres one way of doing it in your controller. Note this: $getID['orgID'] is very awkward. You are getting results back from the members table so call it members.
// check for the negative first - if no members came back
if( ! $members = $this->userModel->getOrganizationID($user_id) )
{
// if no results back leave this method
// pass the user id so you can echo it out in the error page
$this->showNoResultsFor($user_id) ;
}
else{
foreach ($members as $member)
{
$org_id = $member->org_id;
// etc etc etc
I'm not a codeigniter expert but looking at your code, I am wondering why you are setting:
$getID['orgID'] = $this->userModel->getOrganizationID($user_id);
First, you are setting an array $getID['orgID'] rather than just using something like $memberships = ...; I'm not sure why you are casting an array.
Secondly, you seem to be referencing a model class without instantiating it:
$this->userModel->getOrganizationID($user_id);
Perhaps codeigniter does some magic? $this refers to this instance and from the code you show, your model is likely in a separate class/file so I am unclear how $this->userModel is referenced in your method, unless you are instantiating it in your Controller's constructor?
From what I see it looks like you are getting the error because you are not supplying a valid object/array to your foreach. Perhaps start by testing you are actually getting a valid return from $this->userModel->getOrganizationID($user_id).

YII: Call to a member function offset() on a non-object

I am very new to php and yii2, i am trying to read all data records by active record
The code below give error Call to a member function offset() on a non-object
$cmylist = ClassInfo::find()->all();
$pages = new Pagination(['totalCount' => count($cmylist)]);
$models = $cmylist->offset($pages->offset)->limit($pages->limit)->all();
Seems cmylist is a array and i can not call offset and count on it
This is really made me crazy, thanks for your help
Of course, if You call all() it's create final result. Call ->offset() before ->all()
just see
http://www.yiiframework.com/doc-2.0/yii-data-pagination.html
Calling all() returns array of result models, You need to adjust Your code this way:
$cmylist = ClassInfo::find(); //activeQuery instance
$pages = new Pagination(['totalCount' => $cmylist->count()]);
$models = $cmylist->offset($pages->offset)->limit($pages->limit)->all();

Solve Call to a member function combinestring() on a non-object

I met a problem when Call to a member function combinestring() on a non-object.
**Index.php**
inlcude("string.php");
calldata('usa');
**string.php**
$a=new a();
funciton calldata($val){
$st1="select a from table 1 where country=".$a->combinestring($val);
return $st1;
}
**Class A**
function combinestring($abc){
Return "'".$abc."'";
}
Unknow $a->combinestring($val);
How to solve this problem.
Best Regards
You're getting error
Call to a member function combinestring() on a non-object
because you are calling a member function on the variable that is not an object. That means $a is not an object.
In string.php , you cannot use $a inside function definition because variable has local scope. You cannot access that object instance like that. You can however do this by using global variable.
Your string.php file should be like this:
$a=new a();
funciton calldata($val){
global $a;
$st1="select a from table 1 where country=".$a->combinestring($val);
return $st1;
}
Head to this link for more information on variable scope: http://php.net/manual/en/language.variables.scope.php
Use PDO.
funciton calldata($val){
$st1="select a from table 1 where country = ?";
$pdo = new PDO('host', 'user', 'pass');
$result = $pdo->prepare($st1)->execute($val);
return $result;
}
This is a lot different from what you are doing, but your a class does not escape the input to the query and that's bad.

CodeIgniter models and properties

I have a question relating to properties for a specific instance of a CI model. For example:
There is a model called project_model. In the model it has a method calle Get_Projects:
$total_projects = $this->project_model->Get_Projects($options);
When this is called it creates a property in the model like so:
$query = $this->db->get('projects');//query
$this->num_rows = $query->num_rows();
return $query->result();
So after the method has been called and in the controller, I need to access num_rows:
$num_rows = $total_projects->num_rows;
(I know some of you may question the reason behind using num rows in the controller. It's to do with setting the pagination. There may be better ways of doing it but there is no time in this particular project.)
My problem is that this creates a syntax error:
Severity: Notice
Message: Trying to get property of non-object
Filename: controllers/projects.php
Line Number: 110 ($num_rows = $total_projects->num_rows;)
Firstly why is this? I was thinking of using this: $this->project_model::num_rows instead? But then the num_rows won't be specific to the $total_rows object will it? So it will just be for the entire model.
BTW: I read the CI guide on models but there wasn't any information on creating instances of models at all.
EDITED: I need the result of num_rows property to be object-specific. So for example:
$a=$this->project_model->Get_Projects($options);
$b=$this->project_model->Get_Projects($options);
$num_rows = $this->project_model->num_rows;
The final line will get the result of $b num_rows and not $a. So How do I call it so that I can make it object-specific? (Obviously I could store it before the second call in a variable.)
This happens because your variable $total_projects doesn't have an instance of the class. It just contains the results from the Get_Projects() function.
You should try, after doing everything, $num_rows = $this->project_model->num_rows (untested)
You could just instantiate a the model each time you need it.
$object_one = new $this->project_model;
$foo = $object_one->Get_Projects($options);
var_dump($foo);
echo $object_one->num_rows;
$object_two = new $this->project_model;
$bar = $object_two->Get_Projects($options);
var_dump($bar);
echo $object_two->num_rows;
This way you can get/set any attributes of each model instance seperatly.
Better way is to make two queries.
One for the num rows and other for the result.
You are returning the result only, not the num rows. So it won't return the value.
Make each query in different function. And then call from that function.
I am not sure about performance side though.
****** Model ****
class Project_model extends .... {
private $num_rows = 0;
public function Get_Projects($options){
.....
$query = $this->db->get('projects');//query
$this->num_rows = $query->num_rows();
return $query->result();
}
public get_num_rows(){
return $this->num_rows;
}
}
**** Controller ****
class Project extends .... {
function project(){
...
$total_projects = $this->project_model->Get_Projects($options);
$num_rows = $this->project_model->get_num_rows();
...
}
}
Not a perfect exaple of encapsulation but....

Fatal error: Call to a member function create() on a non-object in <file>

For a php project I use a Collection class to handle my objects and lazyloading in Java-like collections.
Now my object has a collection of emailaddresses for example. So I call the getEmailAddresses() function of the object which calls the mapper to return a collection of emailaddresses.
This works fine, but when I do a foreach loop over my collection it returns valid data with the following error in the end:
Fatal error: Call to a member function create() on a non-object in /foo/bar/Collection.php on line 89
It directs to the following function:
public function current()
{
if ($this->_collection instanceof Iterator)
$key = $this->_collection->key();
else
$key = key($this->_collection);
if ($key === null)
return false;
$item = $this->_collection[$key];
if (!is_object($item)) {
$item = $this->_gateway->create($item);
$this->_collection[$key] = $item;
}
return $item;
}
This line:
$item = $this->_gateway->create($item);
The _gateway is the adapter the collection uses. Which I don't use and keep it null. Maybe it has something to do with that?
Anybody has some clue? Because everything is functioning as it should, I can read the collectiondata. It's just the error.
Replace
if (!is_object($item))
with
if (!is_object($item) && !is_null($this->_gateway))
This of course only makes sure the code doesn't get called if gateway isn't set, so it doesn't do anything to $item (which might not be what you want).
Already got it!
It appears that if the collection requested doesnt have any objects, it just tries to do something.
If I first count the items and compare it to > 0 it doesnt return any errors. This is going to be an issue so I'll update the class to check for it first.
I'm not the only one working with it, this is not an error you would expect.
This only means that $this->_gateway is not an object and it should be. It can't be null.
You can change this line:
$item = $this->_gateway->create($item);
to
if(is_object($this->_gateway)) {
$item = $this->_gateway->create($item);
}
this will fix this error, but can lead to more errors further down, depending on what exactly is $item supposed to be.

Categories