问题
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