doutong7216 2013-01-05 16:07
浏览 10
已采纳

查询功能神秘破解[关闭]

I have a Database class which has multiple functions to execute queries. One of them is the simplest of them all:

public function query($query) {
    return $this->_link->query($query);
}

$this->_link->query works in other cases, so it should work here. From a file that has an instance of a class, I do this:

function createLineChart() {

    $query = "select * from tags";
    $result = $db->query($query);

    // do something with result
}

createLineChart();

but it breaks on the $result line. The query is also valid, I've testid it. Am I missing something?

  • 写回答

3条回答 默认 最新

  • duanci1939 2013-01-05 16:27
    关注

    Your problem is $db is out of scope of the createLineChart() function. You can either use the global method:

    function createLineChart() {
        global $db; // <-- make the db var become available
        $query = "select * from tags";
        $result = $db->query($query);
    
        // do something with result
    }
    

    Or pass the $db object to the function as an argument:

    function createLineChart($db) {
    
        $query = "select * from tags";
        $result = $db->query($query);
    
        // do something with result
    }
    
    createLineChart($db);
    

    More info about Variable Scope on the Manual.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?