Generally speaking, there are three ways to deal with this situation with a single request (fewer requests are usually a good thing to shoot), but none of them is a universal βbest wayβ. What you should use depends on your needs.
First, as you noticed, by running INSERT β¦ blindly and handle any PHP errors. This is the best approach when a duplicate key indicates procedural problems (a software bug, a user trying to register a name that has already been used, etc.), because it allows you to perform additional operations before performing a database update.
Secondly, there is INSERT IGNORE β¦ syntax. I would call this the least common approach, since it completely discards INSERT if the key already exists. It is primarily useful when a row (or rows) can be added or not added to the table earlier, but the data, as you know, has not changed.
Finally, you can use the INSERT β¦ ON DUPLICATE KEY UPDATE β¦ . They can be quite detailed, but very convenient, because they allow you to insert data into a table without worrying about whether older data exists. If so, the existing row is updated. If not, then a new one. In any case, your table will have the most recent data available.
Ben blank
source share