drcrc28428
2018-04-04 12:14
浏览 108
已采纳

从STDClass获取价值

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

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duandgfh0506 2018-04-04 12:41
    已采纳

    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;
        }
    
    点赞 打赏 评论
  • dongzhu0327 2018-04-04 12:17

    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;
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题