I understand why we should not loop MySQL queries and I am trying to avoid it. I have an array $names which contains a list of keywords to insert into someTable, with a UNIQUE constraint on the MySQL field name:
mysql> select * from someTable where name='stress';
+-----+--------+
| id | name |
+-----+--------+
| 143 | stress |
+-----+--------+
1 row in set (0.00 sec)
mysql> insert into someTable (name) values ('stress');
ERROR 1062 (23000): Duplicate entry 'stress' for key 'name'
mysql>
I would prefer a query of the following type to avoid a loop:
$result = mysql_query("insert into someTable (name) values ('firstName'), ('secondName'), ('thirdName')");
However, if any of the names already exist then none of the values get inserted. Furthermore, the value of $result will be FALSE. How can I construct a single query to insert the values, which will not fail if any of them exist, and which will return TRUE if any of them were inserted?
I know that I could write a stored procedure for this, but that would just move the loop from PHP to MySQL. Other than bandwidth (not critical as this is on localhost) that doesn’t seem to save anything.
If there is a duplicate, it will ignore and continue.