Search code examples
phpsqlon-duplicate-key

'insert into ... on duplicate key' with auto increment


I am trying to do an INSERT only if the combination of two columns (a and b) does not exist already. Otherwise, I want to do an UPDATE. The issue of the following code is that it always INSERTs a new row instead of updating when I want to. The reason I think, is because I don't manage do have a kind of two-unique-column in the settings of my table. Does any one have a solution? Google doesn't seem to be my friend today..

The table:

id : int, primary,  AI
a b c and d : int

The code:

$req = $connexion -> prepare("
INSERT INTO position (a,b,c,d)
VALUES (:a,:b,:c,:d)
ON DUPLICATE KEY UPDATE
c=:c;");
$position->bindParam(':a', $a);
$position->bindParam(':b', $b);
$position->bindParam(':c', $c);
$position->bindParam(':d', $d);
$a = $val_a;
$b = $val_b;
$c = $val_c;
$d = $val_d;
$req -> execute();

Solution

  • ON DUPLICATE KEY requires a UNIQUE KEY if you are not matching to the PRIMARY KEY. You can add a UNIQUE KEY by using an ALTER TABLE query

    ALTER TABLE position ADD UNIQUE KEY (a,b)