duanjian7343 2013-05-13 21:17
浏览 21
已采纳

想在报告中看到SQL错误

I have a query

INSERT INTO table (id) VALUES (5);

The table already has a record with such ID. So the query fails.

My mysqli class extension looks like this:

<?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
    }
}

Right after $mysqli->execute() I log $mysqli->error and get:

*Unknown prepared statement handler (0) given to mysqld_stmt_execute*

But I would like to see the SQL error instead:

Duplicate entry '5' for key 'PRIMARY'

  • 写回答

1条回答 默认 最新

  • douqiao5552 2013-05-14 05:24
    关注

    There is not much sense in the first block actually. Look what you're doing:

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

    "if there is no $st object - call this object's method".

    Next one is better but anyway - there is no error method or property in mysqli_stmt class.

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

    Exceptions are better as they can be caught and contain a stack trace out of the box.

    By the way, there is no point in using prepare() without parameters. So, the code actually have to be

    function exe($sql) {
        if ( ! $this->DB->query($sql) ) {
            throw new Exception($this->DB->error);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?