调用非对象,实际上是一个对象

时间:2012-06-29 07:20:57

标签: php

我的php脚本有问题。 问题在于它告诉我,我正在调用非对象的函数,但该对象存在。

脚本是:

if ($dcdt_sql['pdo']) {
try {
    $dbh = new PDO(
        'mysql:host='.$dcdt_sql[0].';dbname='.$dcdt_sql[3],
        $dcdt_sql[1],
        $dcdt_sql[2],
        array(
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8",
            PDO::ATTR_PERSISTENT => false
        )
    );
}
catch (PDOException $e) { die("PDO ERR: [".$e->getMessage()."]"); }
}
else { $dbh = DBManager::connect(); }

switch ($mode) {
case 'fetch_assoc':
    if ($dcdt_sql['pdo']) {
        try {
            $sth = $dbh->prepare($sqlQuery)->execute();
            $result = $sth->fetchAll(PDO::FETCH_ASSOC); // PROBLEM IS IN THIS LiNE
            $return = $result;
        }
        catch (PDOException $e) { die("PDO ERR: [".$e->getMessage()."]"); }
    }
    else {
        $result = $dbh->query($sqlQuery);
                    if (!is_object($result)) { die('DEBUG: Query error: ['.$sqlQuery.'] returned: ['.print_r($result,1).']'); }//DEBUG
        while ($row = $result->fetch_assoc()) {
            $list[] = $row;
        }
        $return = $list;
    }
break;

问题是我评论它的地方,但它应该是一个调用函数的对象。 所以我不明白。

我得到错误:

致命错误:在第102行的/usr/local/www/apache22/data/centrs/dc_elec/report.lib.inc中的非对象上调用成员函数fetchAll()

提前谢谢你。

4 个答案:

答案 0 :(得分:2)

http://sg.php.net/manual/en/pdostatement.fetchall.php

按照规定正确使用:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

答案 1 :(得分:1)

execute方法返回TRUE或FALSE,而不是对象。尝试

$sth = $dbh->prepare($sqlQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

答案 2 :(得分:0)

也许试试

$sth = $dbh->prepare($sqlQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // PROBLEM IS IN THIS LiNE
$return = $result;

答案 3 :(得分:0)

尝试:

        $sth = $dbh->prepare($sqlQuery);
        $sth->execute();
        $result = $sth->fetchAll(PDO::FETCH_ASSOC); // PROBLEM IS IN THIS LiNE
        $return = $result;

这应该有效,因为execute将返回一个布尔值,而不是对象本身。在对其余代码的批评中;当你使用对象时,请查看 polymorphism ,如果将“脏工作”放入专用对象中,则不需要那些if / else语句。