2011-03-16 101 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. 
}