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');";
}
$database->query($q);

I just query once


$q = "REPLACE INTO table (name, name2) VALUES ('value', 'value2');";
$database->query($q);

More info at
http://blogs.coldbuffer.com/inserting-or-updating-records-using-mysql-replace
https://dev.mysql.com/doc/refman/5.0/en/replace.html

Advertisements

About Michal Zuber

Full stack developer, biker and rollerblader. Owner and developer at https://nevilleweb.sk/ Co-founded http://neville.sk/ Blog at https://michalzuber.wordpress.com/
This entry was posted in sql. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s