I am inserting data in the custom table using the $wpdb->insert. However, upon error I don’t seem to get any information from $wpdb->last_error. What could be the cause of this?

I already have this configuration set in wp-config

define('WP_DEBUG', false);
define('SAVEQUERIES', true);

The code is as below:

$result = $wpdb->insert($this->table, $data_);
if (false === $result) {
   error_log($wpdb->last_error);
}

$this->table and $data_ are populated correctly as it runs successfully.
But I don’t seem to get any information on the query that is failed. Is there any way I can get the actual query ran in $wpdb->insert?

Solution

OK so I figured out the problem. Insert query was failing because one of the column data was huge and exceeding the column size of the database. The column was varchar(500) but the actual data was more then 500 characters, thus failing the query. I changed the column to TEXT and insert was successful without errors.

3 s
3

If you want the query, that’ll be $wpdb->last_query (note that you also do not need SAVEQUERIES, that’s only if you want a log of every query ($wpdb->queries)

last_error is… well, the error!

Update: Possible explanation for last_error being empty – this is the source of wpdb::query():

// If we're writing to the database, make sure the query will write safely.
if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
    $stripped_query = $this->strip_invalid_text_from_query( $query );
    // strip_invalid_text_from_query() can perform queries, so we need
    // to flush again, just to make sure everything is clear.
    $this->flush();
    if ( $stripped_query !== $query ) {
        $this->insert_id = 0;
        return false;
    }
}

// Redacted code

// Keep track of the last query for debug..
$this->last_query = $query;

$this->_do_query( $query );

// Redacted code

// If there is an error then take note of it..
if ( $this->use_mysqli ) {
    $this->last_error = mysqli_error( $this->dbh );
} else {
    $this->last_error = mysql_error( $this->dbh );
}

In other words, WordPress seems to pre-emptively check the query and will abort if it deems it will fail – in this case you get your return false but no error will be set (since it was never sent to the MySQL server).

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *