REPLACE instead of SELECT and then INSERT or UPDATE

It's nice that MySQL has the replace query so instead SELECTing to check if the data exists in the DB and than INSERTing or UPDATEing I just need to write one query.

So instead this:
$q = "SELECT id FROM table WHERE name = 'value' AND name2 = 'value2' LIMIT 1;";
$id = $database->get_one($q);
if ($id > 0) {
    $q = "UPDATE table SET name = 'value', name2 = 'value2' WHERE id = $id LIMIT 1;";
else {
    $q = "INSERT INTO table (name, name2) VALUES ('value', 'value2');";

I just query once
$q = "REPLACE INTO table (name, name2) VALUES ('value', 'value2');";

More info at

No comments:

Post a Comment