I have a nested array in php and I’m trying to insert data into a mysql table only if a duplicate does not exist. The duplicate should only check match against the sensor_serial and dates field. I’m having no luck with DUPLICATE as the id is unique regardless of the other fields. this is the table layout:
CREATE TABLE IF NOT EXISTS `temps_test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`sensor_serial` varchar(64) COLLATE latin1_general_ci DEFAULT NULL,
`temp_c` float DEFAULT NULL,
`dates` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `date` (`dates`)
)
This is my non working code. I can’t seem to get it quite right.
foreach ($output as $k => &$v) {
$sql = "INSERT INTO temps_test (sensor_serial,temp_c,dates) VALUES ('$v[7]','$v[3]','$v[5]') WHERE NOT EXISTS (SELECT * FROM temps_test WHERE sensor_serial='$v[7]' AND dates='$v[5]')";
$go = mysql_query($sql) or die( mysql_error() );
}
Can this be done this way or is my approach totally off?
Try using
ON DUPLICATE KEY UPDATEmake sure to add constraint on field
sensor_serial, example