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.

Stefan
  • 2,164
  • 1
  • 23
  • 40
  • 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). – N.B. Mar 29 '12 at 13:44

1 Answers1

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.

erdeszt
  • 799
  • 5
  • 12
  • I think Codeigniter's Active record class unfortunately doesn't have this feature – Stefan Mar 29 '12 at 13:49
  • 1
    Check the last answer on this thread: [http://stackoverflow.com/questions/3361490/how-would-i-use-on-duplicate-key-update-in-my-codeigniter-model](http://stackoverflow.com/questions/3361490/how-would-i-use-on-duplicate-key-update-in-my-codeigniter-model) – erdeszt Mar 29 '12 at 13:51
  • I'll have a look at it, Thanks! – Stefan Mar 29 '12 at 13:54