SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru
    Join Date
    Feb 2008
    Posts
    655
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Inserting if data doesn't already exist

    I have an SQL query like this:

    Code MySQL:
    INSERT INTO contacts (id, name, email, user, date_added) VALUES('', 'test', 'test_user@example.com', 1, NOW())

    The fields in order are:
    id, name, email, user, date_added

    I want to only have this data inserted if the email doesn't already exist for that particular user (1 in this example). This means that the email field isn't unique as such. Just that the data should only be inserted if it doesn't exist for this particular user.

    If anybody has any ideas I would greatly appreciate it.

  2. #2
    SitePoint Zealot sdlifecycle's Avatar
    Join Date
    Sep 2006
    Location
    Minnesota
    Posts
    129
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can use EXISTS clause to check for existing row. Otherwise, check this link out for another way that allows you to update if you do find existing row. You can remove that if its not needed:

    http://www.jumpingbean.co.za/blog/my...te-else-insert

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    declare a unique compound index across user,email

  4. #4
    SitePoint Wizard PHPycho's Avatar
    Join Date
    Dec 2005
    Posts
    1,200
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    If you want the insert and update with a single go then i would prefer to wrap it by a function, suppose say: save($table, $associative_array, $id)
    if $id is set then update the data array else insert the data array in the corresponding table.

    Hope this helps.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •