I have a system that involves an ajax post request that inserts a row into a table. It seems that sometimes the ajax call is called twice, meaning that the same data is inserted twice in two adjacent rows.
I’m planning to add a query first to try and select a row with the same data, then if the number of rows = 0 add it. Is there a better way that avoids having to do two queries?
You can use the INSERT IGNORE INTO syntax or INSERT…ON DUPLICATE KEY UPDATE on your insert statement.
If you use INSERT IGNORE, then the row won’t actually be inserted if it results in a duplicate key. But the statement won’t generate an error. It generates a warning instead.