SebastianOpperman
SebastianOpperman

Reputation: 7336

SQL Update if already exists, else insert

I have the following sql statement:

$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')";

This is just a basic INSERT sql. Is there a way for it to Update a record if the 'variant_id' is already present. If the 'variant_id' is not already there it should Insert a new one.

Any help would be appreciated

Upvotes: 2

Views: 2379

Answers (3)

Andreas Rohde
Andreas Rohde

Reputation: 609

In MySQL you can use ON DUPLICATE KEY

INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')";

ON DUPLICATE KEY UPDATE `code`=VALUES(`code`);

In T-SQL (2008 an higher) you could use MERGE

Upvotes: 2

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

$sql = "INSERT INTO jos_vm_product_details (variant_id, global_variant_id, 
                  code, size, details, color, top, price) 
        VALUES ('$variant_id', '$global_variant_id', '$code', '$size', 
                '$details', '$color', '$top', '$price')
        ON DUPLICATE KEY UPDATE
          global_variant_id = VALUES(global_variant_id),
          code = VALUES(code),
          size = VALUES(size),
          details = VALUES(details),
          color = VALUES(color),
          top = VALUES(top),
          price = VALUES(price)";

Upvotes: 4

xdazz
xdazz

Reputation: 160963

You can check INSERT ... ON DUPLICATE KEY UPDATE

Upvotes: 4

Related Questions