2013-05-13 52 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