我对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()
提前谢谢你。
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);
execute 方法返回 TRUE 或 FALSE,而不是对象。尝试
$sth = $dbh->prepare($sqlQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
也许可以尝试
$sth = $dbh->prepare($sqlQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // PROBLEM IS IN THIS LiNE
$return = $result;
尝试:
$sth = $dbh->prepare($sqlQuery);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // PROBLEM IS IN THIS LiNE
$return = $result;
这应该有效,因为 execute 将返回布尔值,而不是对象本身。对代码其余部分的批评;当你使用对象时,请查看多态性,如果你把"脏工作"放到专用对象中,这些if/else语句应该是不必要的。