0

我有一个查询

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并得到:

*给mysqld_stmt_execute的未知准备语句处理程序(0)*

但我想改为查看 SQL 错误:

键“P​​RIMARY”的重复条目“5”

4

1 回答 1

1

实际上,第一个区块没有多大意义。看看你在做什么:

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

“如果没有$st 对象 - 调用这个对象的方法”。

下一个更好,但无论如何 - 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);
    }
}
于 2013-05-14T05:24:01.087 回答