Categories: Development

PHP PDO INSERT on duplicate UPDATE

A MySQL INSERT on duplicate key UPDATE is an all-round excellent query because if a key already exists it will update set values instead of inserting or returning an error.

This query works on tables that have Unique indexes and primary keys.

An example of this being you are inserting products and their identifier is pid (product id). The product specs may change through time and you’re unsure if it’s even in your database.

Using the insert on duplicate key update query means that if that product (pid) is already in your database then the specs will be updated.

<?php
$query = $db->prepare('INSERT INTO products (pid, weight, price, h_w) VALUES(:var, :var2, :var3, :var4)
    ON DUPLICATE KEY UPDATE weight = :var2, price = :var3, h_w = :var4');
$query->bindParam(':var', $avar, PDO::PARAM_INT);
$query->bindParam(':var2', $avar2, PDO::PARAM_STR);
$query->bindParam(':var3', $avar3, PDO::PARAM_STR);
$query->bindParam(':var4', $avar4, PDO::PARAM_STR);
$query->execute();

The above prepared statement updates the: weight, price and h_w if the product already exists in the database.

In certain situations, this query can prevent you from needing to do a row count to determine if an INSERT is needed or an UPDATE instead.

However, the documentation does state to avoid using this query on tables that have multiple unique indexes.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago