Schonhose

Home | PP Addons| Gallery | Photoblog

MySQL tip: Insert or update

February 1, 2008
php.png

Back in the old days (like yesterday) I pretty much used the same code for checking if we should do an insert or an update of a row over and over again. I just would copy the following code:


$sql = 'SELECT `a` FROM `table` WHERE `a` = 1';
$result = mysql_query($sql);
if(mysql_num_rows($result) == 1) {
// do an SQL UPDATE
}
else {
// do an SQL INSERT
}

Nothing wrong with this code, but it seems there is a better and faster way, the ON DUPLICATE KEY UPDATE . This makes it much easier:

$sql = 'INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE c=3';

Prior to this you have to set one column to UNIQUE. Let’s assume we set `a` as an unique column. If MySQL tries to insert another row with `a` having the value 1 it will automatically continue to the UPDATE statement so it sets `c` = 3 where `a` = 1.

If the value for `a` doesn’t exists a new row is added. Pretty sweet stuff. =D

Categories
Programming
Tags
PHP

« Television quotes Pixelpost addon: Googlemap »

Navigation

  • Miscellaneous
  • Photography
  • Programming
  • Website

Countdown:

    No dates present

Tagcloud

3g addon allergic rhinitis backup basketball battery replacement Bob Marley budweiser bug Defensio design ebay exposition googlemaps HDR King layout update Lightroom Miscellaneous music paypal personal photoblog Photography Photoshop PHP Pixelpost pollens preview quote rant Touch UNC update videoclip vote Website Wordpress youtube

Flickr: latest uploads

Dutch landscape (HDR)Bottles and milk storage"Screaming Eagles"Douglas C-47 SkytrainDouglas C-47 Skytrain"De Toekomst"FireworksAppartment building by night.BumblebeeMoon over deserted rail road station
 

Paypal Donations

Why donate? Any donation will be considered a motivation to continue providing support and writing more plugins.

Please remember: it is not the amount but the thought that counts!
Amount: $

Twitter:

No public Twitter messages.

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox