Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CodeIgniter - continue on SQL error?

Basically I have a table with a couple of columns marked Unique. I have a script that dumps a bunch of values into the table with a command like this:

$this->db->query("INSERT INTO `table` (`col1`, `col2`, `col3`) VALUES (`val1`, `val2`, `val3`)");

Every so often my script will try to insert a row which would violate the uniqueness of one of the columns. However, instead of causing the script to abort with a database error, I'd like it to continue, possible outputting a little message. Basically I'm looking for the codeigniter equivalent of

mysql_query("INSERT blah blah blah") or print("fail");

Thanks!
Mala

like image 859
Mala Avatar asked Dec 12 '09 13:12

Mala


People also ask

How do I enable error reporting in CI?

You can configure your CI log file by going to the config. php file in your applications/config directory and set value to $config['log_threshold'] . For a live site, you'll usually only enable Errors (1) to be logged otherwise your log files will fill up very fast.


2 Answers

Yeah, took me a while too and annoyed the hell out of me:

$db['default']['db_debug'] = FALSE;

... in config/database.php - disables the error page.

After a query ran, use this to check for an error:

if (!empty($this->db->_error_message())) {
    echo "FAIL";
}
like image 138
Till Avatar answered Sep 20 '22 19:09

Till


I know you already have a solution, but thought this might be useful for others viewing this question as well.

Let the database do the work for you:

$this->db->query("INSERT IGNORE INTO `table` (`col1`, `col2`, `col3`) VALUES (`val1`, `val2`, `val3`)");

When you use INSERT IGNORE, things like duplicate key errors become warnings instead of errors, which let your queries run without interrupting the flow of your script.

You could then do a

SHOW WARNINGS;

after all the queries have run to see what warnings occurred.

http://dev.mysql.com/doc/refman/5.1/en/insert.html

like image 23
bradym Avatar answered Sep 23 '22 19:09

bradym