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

从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;
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献