2012-06-29 43 views
-5

我有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; 

問題出在哪裏我評論它,但它應該是一個對象衛生組織函數被調用。 所以我不明白。

錯誤,我得到:

致命錯誤:調用非對象/usr/local/www/apache22/data/centrs/dc_elec/report.lib.inc上一個成員函數使用fetchall() 102行

謝謝你提前。

+2

http://sg.php.net/manual/en/pdostatement.execute.php'execute()'返回一個布爾值,以便錯誤消息是正確的。 –

+1

這就是你得到的方法鏈接。不要這樣做,否則你將無法輕鬆發現這樣的錯誤。 – PeeHaa

+4

口譯員不說謊 – Gordon

回答

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); 
+0

感謝您的快速回復。 – dpitkevics

0

也許嘗試

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

execute方法返回TRUE或FALSE,而不是對象。嘗試

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

嘗試:

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

這應該工作,如執行會返回一個布爾值,而不是對象本身。對其他代碼進行批評;當你使用對象時,請查看多態性,如果將「髒工作」放入專用對象中,那麼if/else語句不應該是必需的。

相關問題