【问题标题】:Having troubles with mysqli::fetch_object();mysqli::fetch_object() 有问题;
【发布时间】:2013-11-01 02:30:23
【问题描述】:

在 Google 上阅读了 5 个小时后,我无法用 MySQLI 修复问题。

我一生都在 MySQL 编程,现在我正在尝试使用 mysqli 更新我的知识,但我遇到了一些麻烦。

我有一个名为 news_Default() 的小函数,如下所示:

    <?php 
    Class Test extends DB{
    public function news_Default(){
        $query = $this->db->query('SELECT * FROM news');
        if($query->num_rows == 0)
            return false;
        else
            return $query->fetch_object();
        }
    }
    ?>

而我是这样使用的:

    <?php
    while($new = $panel->news_Default()){
        print_r($new);
    }
    ?>

在 MySQL 中,当我返回对象时,我可以将它与 'while' 或 'foreach' 循环一起使用而不会出现问题,但真正的问题在这里,使用 mysqli。

当我使用“while”(第二个代码块)时,它循环了 6,000 次(我使用了 $counter++ 来测试它),而当我使用 foreach 时,它正好循环了 7 次。在我的名为“新闻”的表中,我只有两条记录。那么,我怎样才能返回对象并在外面使用它而不会出现这个问题呢?因为当我在 $new = $query->fetch_object() 之类的类中使用它时,效果很好。

【问题讨论】:

  • 你的php版本是多少?

标签: php mysqli


【解决方案1】:

每次调用news_Default时都是在做sql查询。

修复它的示例。

Class Test extends DB{
    private $_cached_news = null;                    // let's store our query result
    public function news_Default(){
        if ($this->_cached_news === null){           // not stored?
            $this->_cached_news = $this->db->query('SELECT * FROM news');} // let's query
        $return = $query->fetch_object();            // get next object
        if (!$return)                                // there is no objects anymore?
            $this->_cached_news = null;              // let's clear our result
        return $return;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-26
    • 1970-01-01
    • 2011-11-02
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多