2

I always end up with errors in my CodeIgniter log such as

ERROR - 2011-04-12 00:06:44 --> Query error: Duplicate entry '1391280167' for key 1

But it's not much help without context. Is there any way to record the query as well that caused this error?

3 Answers 3

2

I just took a quick peek inside the system/database/DB_Driver.php (line 323) file and it doesn't log the SQL query with any settings you choose. It should however print these messages to the screen if you are in db_debug mode.

If you don't mind messing with the files in the CI system folder, you could get the sql statement in your log file by changing system/database/DB_Driver.php (line 323, for CI 2.0.1) to:

log_message('error', 'Query error: '.$error_msg. ' - '. $sql);
Sign up to request clarification or add additional context in comments.

Comments

1

As a start, you can get the last query that was run using $this->db->last_query()


So we could get the query as a string with the following snippet:

// strip out line returns, new lines and tabs
$query = str_replace( array("\r", "\n", "\t"), '', trim($this->db->last_query()) );

Once you have a string, we can log to the error log:

error_log( "Last database query: " . $query );

Note: Depending on your application logic and traffic, this could add tons of extra bloat to the error log over time, so I would recommend this is only used as a temporary troubleshooting tool.

Hope that helps.

Comments

0

Check if you have defined Auto Increment for the Primary Key, in the table in which you insert.

5 Comments

I have not. I have many tables with many UNIQUE indexes, so it's difficult to find it. Being able to see the query would make things tons better.
Set your error reporting of Codeigniter to E_ALL and make sure the db_debug in database.php file is set to TRUE.
Check this extension for CI error handling: hg.dhorrigan.com/codeigniter-uhoh/src
I have E_ALL and db_debug enabled, but the query does still not show. Thanks for the link to the extension Marko, this is a possible solution. Is there no native way to get this functionality though?
@Marko Aleksić: the link is dead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.