Geo
Geo

Reputation: 13006

want to see SQL error in report

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'

Upvotes: 0

Views: 182

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157868

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);
    }
}

Upvotes: 1

Related Questions