Reputation: 21
I'm trying to insert a couple of values into a table via PHP as follows:
$sql = "INSERT INTO table1(Field1, Field2)
Values (?, ?)
";
$stmt = $db-> prepare($sql);
$stmt->execute(array($field1, $field2));
$stmt->closeCursor();
Field 1 is a primary key.
However, I only want to insert Field1 if there is not already an instance of that record for field1 in the table (for example, if there's already a field1 record as 'orange' it should not insert another 'orange' if asked to do so).
I feel like this must be pretty straight forward to do but nothing I'm trying seems to be working.
Upvotes: 1
Views: 775
Reputation: 27467
Try this
INSERT INTO table1(Field1, Field2)
SELECT @field1, @field2 from dual
WHERE not exists (select 1 from table1 where field1 = @field1);
--@field1, @field2 are your parameter values
Upvotes: 1