0

after reading like 5 hours on Google I can't fix something with MySQLI.

I spent all my life programming in MySQL, and now I am trying to update my knowledge using mysqli but I have some troubles.

I have a little function called news_Default() like this:

    <?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();
        }
    }
    ?>

And I used in this way:

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

In MySQL, when I return the object, I can use it with 'while' or 'foreach' loop without problems, but the real problem is here, with mysqli.

When I used the 'while' (second codeblock), it loops 6,000 times (I used a $counter++ to test it), and when I used foreach, it loops exactly 7 times. In my table called 'news' I have only two records. So, how can I return the object and use it outside without having this problems? Because when I use it inside the class like $new = $query->fetch_object() works perfect.

4

1 回答 1

0

每次调用时都在进行 sql 查询news_Default

修复它的示例。

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;
        }
    }
于 2013-11-01T02:43:29.290 回答