Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal database API query - row.update if exists, else row.insert

I've been trying to run a query in drupal that'll update entries if they already exists or insert a new entry if it doesnt. The code looks like this at the moment:

db_query("IF EXISTS (SELECT %d FROM {uc_posten_packages.pid})
UPDATE {uc_posten_packages} SET title = '%s', label = '%s', cost = '%d', length = '%d', width ='%d', height = '%d', weight = '%d'  WHERE pid = %d
ELSE
INSERT INTO {uc_posten_packages} VALUES ('%d', '%s', '%s', '%d', '%d', '%d', '%d', '%d')",$id, $title, $label, $rate, $length, $width, $height, $weight, $id, $id, $title, $label, $rate, $length, $width, $height, $weight);

I can't see why that query throws me an error. All the numbers in the error are correct

...near 'IF EXISTS (SELECT 1 FROM uc_posten_packages.pid) UPDATE uc_posten_packages ' at line 1 query:
IF EXISTS (SELECT 1 FROM uc_posten_packages.pid) UPDATE uc_posten_packages SET title = 'vfbv', label = 'bbv', cost = '22', length = '232', width ='22', height = '22', weight = '22' WHERE pid = 1 ELSE INSERT INTO uc_posten_packages VALUES ('1', 'vfbv', 'bbv', '22', '232', '22', '22', '22')

Should this query work and/or is there some better way dealing with this in drupal?

like image 387
Toxid Avatar asked Mar 03 '26 03:03

Toxid


1 Answers

What you're looking for is cordially called an "upsert" (update otherwise insert), and there is a drupal function for just this: db_merge. Good write-up here: http://drupal.org/node/310085

drupal_write_record() does not automatically perform an "upsert." It always either inserts or updates based on what you pass in only, but not both.

like image 126
texas-bronius Avatar answered Mar 04 '26 19:03

texas-bronius