2011-03-16 100 views
0

我在這段代碼中得到一個錯誤:拋出一個異常與SQL錯誤消息

try 
     { 
      $db = parent::getConnection(); 
      if($this->id == 0) 
      { 
       $query = 'insert into articles (modified, username, url, title, description, points)'; 
       $query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', '$this->points')"; 

      } 
      else if($this->id != 0) 
      { 

       $query = "update articles set modified = CURRENT_TIMESTAMP, username = '$this->username', url = '$this->url', title = '$this->title', description = '$this->description', points = '$this->points', ranking = '$this->ranking' where id = '$this->id' "; 
      } 

      $lastid = parent::execSql2($query); 

      if($this->id == 0) 
       $this->id = $lastid; 

     } 
     catch(Exception $e){ 
      error_log($e); 
     } 

我有什麼補充,所以我得到了一些有意義的SQL的錯誤信息?

(這似乎對於某些查詢其不獲取用戶名)

編輯:我得到這個錯誤日誌:

[18-Mar-2011 05:19:13] exception 'Exception' in /home1/mexautos/public_html/kiubbo/data/model.php:90 
Stack trace: 
#0 /home1/mexautos/public_html/kiubbo/data/article.php(276): Model::execSQl2('update articles...') 
#1 /home1/mexautos/public_html/kiubbo/data/article.php(111): Article->save() 
#2 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(21): Article->calculateRanking() 
#3 /home1/mexautos/public_html/kiubbo/pages/frontpage.php(27): FrontPage->updateRanking() 
#4 /home1/mexautos/public_html/kiubbo/index.php(15): FrontPage->showTopArticles('426') 
#5 {main} 

謝謝

問候,

卡洛斯

+2

運行代碼時會出現什麼錯誤? – 2011-03-16 12:16:18

+0

什麼是錯誤?????/ – 2011-03-16 12:20:26

+0

當你看到錯誤時,$ query變量的內容是什麼?如果它有時而不是其他人,那麼它可能是你想要傳遞的值的問題。 – dmcnelis 2011-03-16 12:23:44

回答

2
error_log('Failed to set record in articles table: '. 
      $e->getMessage(). 
      "\n".$query 
     ); 
4

處理此問題的最佳方法是使用數據庫處理程序將引發的自定義異常。

class DatabaseErrorException{ 
    public function __construct($errorMesssage, $query){ 
     throw new Exception($errorMessage . " for query: " . $query); 
    } 
} 

,所以你可以檢測錯誤在你的數據庫庫,扔在那裏,或在你的try語句,你可以有:

if($db->someError) 
    throw new DatabaseErrorException($db->someError, $query); 

和你的catch語句會變成

catch(DatabaseErrorException $e){ 
    error_log($e->getMessage()); 
    //Or whatever handling you wish to do with it. 
}