Jump to content


Photo

If data exists already update, otherwise insert


  • Please log in to reply
1 reply to this topic

#1 Kingskin

Kingskin
  • Members
  • PipPip
  • Member
  • 18 posts

Posted 28 March 2006 - 03:50 PM

Using MySQL & PHP, how can I first, check if a row with a given primary id exists and if so, update it, or if not insert it. Secondly, if data already exists in a given field, I want to append the new data onto it rather than overwrite it.

To clarify a bit, if I have 2 columns: id & value

I want to check if id (primary key) exists in the table.

If it doesn't exist, I want to insert a row with that 'id', and some data into 'values', such as '2 3 7 87'

If it does exist, i want to update the row with that id, the append some data to whats already in the 'value' field, so if the 'value' field already contains the data '2 3 7 87' and i also want to add '13 5 9', i end up with '2 3 7 87 13 5 9' in that column.

Thanks for any help you can give me :)




#2 fenway

fenway
  • Staff Alumni
  • MySQL Si-Fu / PHP Resident Alien
  • 16,199 posts
  • LocationToronto, ON

Posted 28 March 2006 - 09:14 PM

Recent versions of MySQL support INSERT... ON DUPLICATE KEY UPDATE... statements, which for certain cases, is preferable to a REPLACE statement. Check the refman for the appropriate syntax.
Seriously... if people don't start reading this before posting, I'm going to consider not answering at all.




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users