2013-05-13 50 views
0

我有一個查詢希望看到SQL錯誤報告

INSERT INTO table (id) VALUES (5); 

表已經有這樣的ID的記錄。所以查詢失敗。

我的mysqli類擴展看起來是這樣的:

<?php 

class my_mysqli extends mysqli { 

    function __construct($config) { 
     $this->DB = parent::__construct($config['HOST'], $config['USER'], $config['PASS'], $config['DB']); 
    } 

    function exe($sql) { 
     if (! $st = $this->DB->prepare($sql)) { 
      trigger_error($st->error); // this one isn't triggered 
     } 
     if (! $st->execute()) { 
      trigger_error($st->error); // this one is triggered 
     } 
     // ..then parse results and close 
    } 
} 

$mysqli->execute()我登錄$mysqli->error,並得到後:

*未知事先準備好的聲明處理器(0)給mysqld_stmt_execute *

但我希望看到SQL錯誤,而不是:

重複條目'5'爲鍵「P​​RIMARY」

+3

顯示您的實際代碼。看起來你沒有正確地準備一個陳述,然後以某種方式錯誤地執行它。 – 2013-05-13 21:19:38

回答

1

實際上在第一個塊中沒有多少意義。看你在做什麼:

if (! $st = $this->DB->prepare($sql)) { 
    trigger_error($st->error); // this one isn't triggered 
} 

「如果沒有$第一對象 - 調用這個對象的方法」。

下一個更好,但無論如何 - mysqli_stmt類中沒有錯誤方法或屬性。

function exe($sql) { 
    if (! $st = $this->DB->prepare($sql)) { 
     throw new Exception($this->DB->error); 
    } 
    if (! $st->execute()) { 
     throw new Exception($this->DB->error); 
    } 
} 

例外情況會更好,因爲它們可以被捕獲幷包含開箱即用的堆棧跟蹤。

順便說一下,使用不帶參數的prepare()沒有意義。所以,代碼實際上必須是

function exe($sql) { 
    if (! $this->DB->query($sql)) { 
     throw new Exception($this->DB->error); 
    } 
} 
+0

完美!非常感謝你! – Geo 2013-05-14 16:42:25