Page 1 of 1

UPDATE or INSERT

Posted: Wed Feb 11, 2009 12:52 pm
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

Re: UPDATE or INSERT

Posted: Wed Feb 11, 2009 12:57 pm
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

Re: UPDATE or INSERT

Posted: Wed Feb 11, 2009 3:31 pm
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?