tags:

views:

59

answers:

3

I have a product info table with more than 130 columns/fields.

I want to write a php script that adds a new product to the table OR updates the existing product if it already exist. The first field is the product key.

The product information is stored in a numbered php array : $product_info[0] to $product_info[130].

Basically something like this :

INSERT INTO table (a,b,c) VALUES ($product_info[0],$product_info[1],$product_info[2])
  ON DUPLICATE KEY UPDATE a='$product_info[0]', b='$product_info[1]', c='$product_info[2]'

Is there something more efficient than typing each of the 130 fields twice?

A: 

Unfortunately MySQL does not support merging... having an ORM can help ease the pain of coding multiple IF EXISTS UPDATE ... ELSE INSERT code

Chris
+1  A: 

Yes, there is, use the VALUES() function:

INSERT INTO `table` (a, b, c) VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)

Basically, in the UPDATE part, VALUES(column) will return the specified value for that column for the current row in question. So you can do interesting things like:

ON DUPLICATE KYE UPDATE 
    a = VALUES(a), 
    b = VALUES(b) + VALUES(c), 

The beauty of that syntax, is it also supports multiple insert rows:

INSERT INTO `table` (a, b, c) 
    VALUES (?, ?, ?), 
    VALUES (?, ?, ?), 
    VALUES (?, ?, ?)
    ON DUPLICATE KEY UPDATE a = VALUES(a), b = VALUES (b), c = VALUES(c)
ircmaxell
Thanks for your reply but I would still have to type all 130 fields twice. This is basically the solution I posted in my question with a little twist. I'm looking for something more efficient if it's doable.
Enkay
A: 

REPLACE

TRiG
No. Don't use `REPLACE` if you care about referential integrity. It deletes if exists, then inserts. So it'll destroy any foreign key relations.
ircmaxell
Right now the php code checks if the row exists. If it does not exist, it does an INSERT. If it does exist, it does a DELETE query followed by an INSERT query.
Enkay