Get value from STDClass

一笑奈何 提交于 2021-02-08 12:01:40

问题


I'm using PHP and CodeIgniter. I ran a query using the following script:

$query = $this->db->query('select login_id, date_created from prjsite_login');
$row = $query->result();
print_r($row);

The result of the print_r is:

Array ( [0] => stdClass Object ( [login_id] => admin [date_created] => 2018-04-04 13:18:42 ) )

Which is correct. Thou when I tried to fetch 1 object or value from stdClass using the following script:

echo $query->login_id;

I received an error below:

A PHP Error was encountered

Severity: Notice

Message: Trying to get property of non-object

Filename: pages/home.php

Line Number: 21

Backtrace:

File: C:\xampp\htdocs\BMI_PRJSITE\application\views\pages\home.php Line: 21 Function: _error_handler

File: C:\xampp\htdocs\BMI_PRJSITE\application\controllers\Pages.php Line: 11 Function: view

File: C:\xampp\htdocs\BMI_PRJSITE\index.php Line: 315 Function: require_once

What am I doing wrong?

TIA


回答1:


You cannot directly get a value from $query because at this point you are just generating a query and you will get the result from $query only after executing it which you are doing at

$row=$query->result();

Looking at your result you are getting a result as an array of a stdClass object so need to json-encode your object and then decode it back to an array

$array = json_decode(json_encode($row), True);

If you are sure you will get only one row then no need for loop and you can simply do it by

echo $array[0]->login_id;

otherwise, you have to go for a loop

 foreach ($array as  $value) {
        echo $value->login_id;
    }



回答2:


As your result is in array and array contain object your have to first access that array then object

echo $row[0]->login_id;

Or use foeach to get all values

foreach($row as $value)
{
    echo $value->login_id;
}


来源:https://stackoverflow.com/questions/49650754/get-value-from-stdclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!