UPDATE or INSERT

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
jwerre
Forum Newbie
Posts: 18
Joined: Thu Feb 05, 2009 5:06 pm

UPDATE or INSERT

Post by jwerre »

How do I know whether to update my database of insert a new row?

If someone logs into my site I want to check to see if they already exist in my database if they exist I want to update the user's info and if not I want to insert new user info.

Is this just a simple "if else" in PHP or are there MySQL methods to take care of this kind of thing?

Thanks
Last edited by jwerre on Wed Feb 11, 2009 3:36 pm, edited 1 time in total.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: UPDATE or INSERT

Post by Eran »

You can use INSERT ... ON DUPLICATE KEY UPDATE
This requires having a unique key on the field you are searching by.
Read the manual for more details - http://dev.mysql.com/doc/refman/5.0/en/ ... icate.html
jwerre
Forum Newbie
Posts: 18
Joined: Thu Feb 05, 2009 5:06 pm

Re: UPDATE or INSERT

Post by jwerre »

Code: Select all

mysql_query(" INSERT INTO tb_user (user_id, is_app_added, name_first, name_last, email) 
               VALUES ($user,'$has_added_app','$first_name','$last_name','$email')
            ON DUPLICATE KEY UPDATE email = '$email' ");
shouldn't this update the email address if the user_id already exists?
Post Reply