So, I am writing an SQL Query, as you do, and I have stumbled across an issue. What I am wanting to do is fire a query at the database every time a unique user visits a certain page. The unique-ness is done through session_id(), as that is generally quite reliable.
What I want is an SQL query which inserts a row of data into two columns, but ONLY if those two columns don't already have the same value.
| page_name | user_id |
| page1 | x |
INSERT INTO `page_views` (`page_name`, `user_id`) VALUES ('.$pageName.', \''.session_id().'\')
Use INSERT IGNORE rather than INSERT. If a record doesn't duplicate an existing record, MySQL inserts it as usual. If the record is a duplicate, the IGNORE keyword tells MySQL to discard it silently without generating an error.
Following example does not error out and same time it will not insert duplicate records.
The syntax is simple - just add "IGNORE" after "INSERT" like so:
INSERT IGNORE INTO mytable (pk, f1, f2) VALUES ('abc', 1, 2);
Inserting multiple records When inserting mutiple records at once, any that cannot be inserting will not be, but any that can will be:
INSERT IGNORE INTO mytable (pK, f1, f2) VALUES ('abc', 1, 2), ('def', 3, 4), ('ghi', 5, 6);
In the second example above, if records already existed for 'abc' and 'def' then those two records would not be inserted, but the record for 'ghi' would be.