1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

MySQL INSERT help

Discussion in 'MySQL' started by rederick, May 4, 2006.

  1. #1
    Hi, I have a question about a MySQL INSERT statement.

    I've got a database that I need to update daily. There is a field that is unique to each record, lets call id the id field, now When I get the new data I want to do an INSERT INTO but instead of adding another entry if that entry already exists then I want to Update that entry. Is there a way I can tell MySql to do this?

    Thanks...
     
    rederick, May 4, 2006 IP
  2. ServerUnion

    ServerUnion Peon

    Messages:
    3,611
    Likes Received:
    296
    Best Answers:
    0
    Trophy Points:
    0
    #2
    ServerUnion, May 4, 2006 IP
  3. iTISTIC

    iTISTIC Peon

    Messages:
    140
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can do this, but it will take a series of statements. Not sure what programming language you're using to interface with the database, but basically I'd do this:

    UPDATE tableName
    SET field1 = 'value1'
    WHERE id = idValue

    After you execute that statement, check the amount of rows that were affected. If there were 0 rows affected, then you'll know to perform the insert statement:

    INSERT INTO tableName (id, field1)
    VALUES (idValue, 'value1')
     
    iTISTIC, May 4, 2006 IP
  4. dfsweb

    dfsweb Active Member

    Messages:
    1,587
    Likes Received:
    55
    Best Answers:
    0
    Trophy Points:
    88
    #4
    Yes, or you could run a select query first ....
    "select * from table_name where id=id_value"

    Then, if you are running PHP, use mysql_num_rows($resultset) to check the number of rows for this.

    If this is 1 - Run update query
    If this is 0 - Run insert query

    Hope this helps!
    dfsweb
     
    dfsweb, May 4, 2006 IP
  5. exam

    exam Peon

    Messages:
    2,434
    Likes Received:
    120
    Best Answers:
    0
    Trophy Points:
    0
    #5
    use INSERT ... ON DUPLICATE KEY UPDATE syntax.
     
    exam, May 4, 2006 IP
  6. rederick

    rederick Peon

    Messages:
    128
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Sweet, thanks for all the help guys.. I'll try them out later tonight.

    I did try the ON DUPLICATE KEY UPDATE syntax that would be perfect but my MySQL version is prior to 4.1 :-(

    Thanks again.
    :D
     
    rederick, May 4, 2006 IP