remyremy remyremy - 9 months ago 20
MySQL Question

Trying to get property of non-object displayed with valid object

I'm using Codeigniter and active record and facing a weird issue.

I have the following PHP code:

foreach ($list_all->result() as $all_Array){
$current_r = $all_Array->id_r;
$get_ongoing_loan_player = $this->get_ongoing_loan_player($current_r);
$ongoing_loan_info = $get_ongoing_loan_player->row();
$daily_payment_player = $ongoing_loan_info->daily_payment;

looks like this:

protected function get_ongoing_loan_player($currentID){
$this->db->where('id_r', $currentID);
$query = $this->db->get();
return $query;

But PHP throws an error:

A PHP Error was encountered Severity: Notice Message: Trying to get
property of non-object

returns the following:

object(stdClass)#38 (1) { ["daily_payment"]=> string(5) "38670" } NULL

Please note the
at the end outside the brackets. I haven't been able to find an explanation for this

I have a really similar function just before and it works fine but in that one the
is not there. I'm pretty sure it's caused by that.

I don't need to load the model as it is on the same page (and I tried it didn't help anyway).

My result is an object and not an array so I can't understand the error message...

Answer Source

In the first iteration, $ongoing_loan_info is an object, so it prints out and works correctly. In your second iteration, $ongoing_loan_info is null, so throws an error. You'll want to make sure that the row exists before trying to get data out of it. This ternary will set the player to 0 if it's null, or you can replace it with whatever you want.

$daily_payment_player = $ongoing_loan_info ? $ongoing_loan_info->daily_payment : 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download