10

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

1
  • Ah whatever happened to the answer with the try-catch block? Commented Dec 13, 2009 at 7:45

2 Answers 2

20

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";
}
Sign up to request clarification or add additional context in comments.

4 Comments

If it's NOT empty, fail? That sounds backwards to me, or do I misunderstand how empty() works?
oh sorry i should probably read the entire line before commenting huh ;) Thanks a bunch!
my code looks like this: if (empty($this->db->_error_message())) echo "succeed"; else echo "fail"; but the page fails with a "Fatal error: Can't use method return value in write context"...
ah I just checked if $this->db->_error_message() == '' ad that works :) thanks for the tip on how to do this :)
9

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

2 Comments

That's actually a really good answer! I'm going to keep mine the way it is for now, but I'll definitely use this in the future. Thanks :)
Nice, I actually prefer this answer. <3

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.