簡體   English   中英

引發帶有SQL錯誤消息的異常

[英]Throw an exception with the SQL error message

我在此代碼中出現錯誤:

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}

謝謝,

問候,

卡洛斯

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

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.
}
error_log('Failed to set record in articles table: '.
          $e->getMessage().
          "\n".$query
         );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM