【问题标题】:PHP / Mysql errorPHP/Mysql 错误
【发布时间】:2011-06-17 10:39:48
【问题描述】:

型号

<?php 
class Blogm extends CI_Model{

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    function get()
    {
        $query = $this->db->get('post', 1);
        return $query->result();
    }
}
?> 

查看

<h2>

<?php 
foreach($query as $a):
echo $a;
endforeach;
?>

</h2>
</body>
</html> 

控制器

<?php
class Blog extends CI_Controller{

    public function __construct(){
        parent::__construct();
        $this->load->model('Blogm','',TRUE);
    }
    public function index(){

        $data['title'] = 'Sblog';
        $data['message'] = 'My Sblog';
        $data['menu_item'] = array('home','contact');

        $this->load->view('headerv.php', $data);

        $data['query'] = $this->Blogm->get();

        $this->load->view('bodyv.php', $data);
        //$this->load->view('sidebarv.php');
        //$this->load->view('footerv.php');
    }
}

    ?> 

数据库

id    int(11)            No    None    auto_increment                                  
    title    text
MIME: text/plain    latin1_swedish_ci        No    None                                    
    content    text
MIME: text/plain    latin1_swedish_ci        No    None                                    
    time    timestamp        on update CURRENT_TIMESTAMP    No    CURRENT_TIMESTAMP    on update CURRENT_TIMESTAMP                                  
    posted    int(1)            No    0 

数据库只有一个条目……

这是我的错误..

遇到了 PHP 错误

严重性:4096

消息:stdClass 类的对象无法转换为字符串

文件名:views/bodyv.php

行号:5

【问题讨论】:

  • 你可以看到错误在body.php(view) 文件中,不在模型或控制器中,请向我们展示这个文件。你正在尝试将对象用作字符串
  • opps...我的错误我没注意到。

标签: php mysql codeigniter


【解决方案1】:

即使您在 LIMIT 为 1 的情况下运行 -&gt;get(),它仍会返回一个结果集。

您实际上在做的是,循环遍历您的集合并打印单个对象,除非它具有 toString() 方法,否则这是无法完成的。这就是 CI 抱怨 Object of class stdClass could not be converted to string 的原因。

把你的代码改成

foreach($query as $obj):
   echo $obj->property; //where property is a column
endforeach;

http://codeigniter.com/user_guide/database/active_record.html

【讨论】:

    【解决方案2】:
    foreach($query as $a):
    echo $a;
    endforeach;
    

    错误信息是不言自明的。

    您正在尝试遍历数据库查询对象$query 的成员,并将其成员作为字符串迭代到echo。其中至少有一个是对象,因此是错误。

    相反,使用您的数据库抽象提供的相关 API 函数遍历由 $query 表示的结果集。

    (查看了有关此问题的其他活动,可能是“CI”允许使用循环作为此 API 的一部分。请参阅文档以找到正确的迭代方法。)

    【讨论】:

    • 我要补充一点,如果它是为了调试目的而完成的,那么 print_r($a) 或 var_dump($a) 语句就可以完成这项工作。
    • @regilero:不知道 CI,我无法发表评论。这当然不是一个包罗万象的解决方案。例如mysqli 资源对象就是:资源对象。其中没有直接包含有用的数据。
    【解决方案3】:

    我认为您需要做的就是添加:

    $a->标题或你想要的信息...

    【讨论】:

      猜你喜欢
      • 2013-08-27
      • 2016-09-02
      • 2012-07-24
      • 2023-03-16
      • 1970-01-01
      • 2013-03-12
      • 2014-07-07
      • 2013-03-01
      • 2013-03-13
      相关资源
      最近更新 更多