1

I'm using Codeigniter and the Active Record class to build a simple API in PHP. I got a table where an IP Adress works as a primary key, and here's my question:

Is it better to run a query against the Database to check if the IP exists when the function to insert the data is run, and then perform a second query inserting the data (if the IP doesnt exists) OR Try to insert the Data and parse the Error message for "Duplicate Entry" or something. So i'm only using 1 DB query with this one.

So its basically PHP Validation vs MySQL Validation. So which technique is better and/or faster.

Thanks.

1
  • Personally, I'd use try/catch and parse the duplicate record error message from MySQL. That way you have only 1 query (INSERT INTO..) versus two queries (check if exists, if not insert). Commented Mar 29, 2012 at 13:44

1 Answer 1

1

Consider the use of ON DUPLICATE KEY UPDATE syntax. Read more about this at: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html But if it's not preferable in your case than i would go with php validation because triggering an error in mysql is never a good idea.

Sign up to request clarification or add additional context in comments.

3 Comments

I think Codeigniter's Active record class unfortunately doesn't have this feature
I'll have a look at it, Thanks!

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.