2011-03-03 65 views
0

在這裏post跟進,似乎我已成功地擴展PDO類,擴展PDO類:爲什麼該方法返回0而不是錯誤消息?

class database_extended extends PDO 
{ 

    #make a connection 
    public function __construct($dsn,$username,$password) 
    { 
     try 
     { 
      parent::__construct($dsn,$username,$password); 
      //$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     } 
     catch (PDOException $e) 
     { 
      # call the get_error function 
      self::get_error($e); 
     } 
    } 

    #get the number of rows in a result 
    public function num_rows($query) 
    { 
     try 
     { 
      # create a prepared statement 
      $stmt = parent::prepare($query); 

      # execute query 
      $stmt->execute(); 

      # return the result 
      return $stmt->rowCount(); 
     } 
     catch (PDOException $e) 
     { 
      # call the get_error function 
      self::get_error($e); 
     } 
    } 

    # display error 
    public function get_error($e) 
    { 
     $this->connection = null; 
     die($e->getMessage()); 
    } 

    # closes the database connection when object is destroyed. 
    public function __destruct() 
    { 

    } 
} 

但似乎並不完全正確 - 我在故意查詢錯誤測試num_rows方法,所以這種方法可以返回錯誤消息,

# the host used to access DB 
define('DB_HOST', 'localhost'); 

# the username used to access DB 
define('DB_USER', 'root'); 

# the password for the username 
define('DB_PASS', 'xx'); 

# the name of your databse 
define('DB_NAME', 'xx_2011'); 

# the data source name 
define('DSN', 'mysql:dbname='.DB_NAME.';host='.DB_HOST); 

include 'class_database.php'; 

$connection = new database_extended(DSN,DB_USER,DB_PASS); 

$sql = " 
    SELECT * 
    FROM table_not_exist 
    ORDER BY cnt_id DESC 
    "; 

echo $connection->num_rows($sql); 

它應該返回,

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'xx_2011.table_not_exist' doesn't exist

但是它會返回0!爲什麼??我該如何解決它?

謝謝。

回答

0

PDOStatement::execute當查詢導致錯誤時返回false,它不會引發異常。如果你想對錯誤做些什麼,你應該編寫一些代碼來檢查返回值。

2

因爲PDOStatement::execute不是throw,它只會在失敗時返回false。因此你的代碼永遠不會進入catch塊。應該更多地沿着這條線:

$stmt = parent::prepare($query); 

if (!$stmt->execute()) { 
    self::get_error(); 
} 

return $stmt->rowCount(); 
+0

謝謝deceze。我試過了,但是我有這些錯誤 - '注意:未定義的變量:e在C:\ wamp \ xxx \ class_database.php行xx'和'致命錯誤:調用成員函數getMessage() C:\ wamp \ xxx \ class_database.php on line 141' – laukok 2011-03-03 02:54:47

+0

@lau啊,當然,是的。既然它不會拋出你也沒有得到'$ e'變量。你將不得不重新設計你的錯誤處理程序,以免期望異常。 – deceze 2011-03-03 02:57:15

+0

謝謝。我會嘗試......謝謝! – laukok 2011-03-03 03:01:45

相關問題