|  | Posted by Gordon Burditt on 10/09/05 09:52 
>I am writing an app in PHP that uses a PostGres database.>One thing i have noticed is that what should/could be a single line of
 >SQL code takes about 6 lines of PHP.  This seem wasteful and redundant
 >to me.
 >
 >Here is a sample of what I'm talking about ($db is a PDO already
 >defined and created).
 >
 >$query[1] = "UPDATE my.table, SET somefield = '$someval' WHERE
 >somecondition";
 >$query[2] = "INSERT INTO my.table (somefield) VALUES ('$someval')";
 >if(!$db->query($query[1])){
 >    $db->query($query[2]);
 >}
 >
 >What I'm curious to know is if there is some way to simplify this,
 >either buy some PHP builtin or extension, or possibly something in SQL
 >I am missing.  It seems to me that "UPDATE OR INSERT", should be valid,
 >but I can't seem to find anything relevant at all about it.
 
 MySQL permits (but it's not standard, and available in MySQL 4.1.0
 and later):
 
 INSERT INTO my.table (somefield) VALUES ('$someval') ON DUPLICATE
 KEY UPDATE somefield = '$someval';
 
 This is very useful for times when you want to count something (e.g.
 SPAM), and if a record doesn't exist, make one with a count of 1.
 
 I don't know whether something similar is available in PostGres.
 
 Gordon L. Burditt
 [Back to original message] |