on duplicate key update only null values

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kimberly
    New Member
    • Jun 2011
    • 2

    on duplicate key update only null values

    I am relatively new to php and mySQL. I have a database with a user form used to update and create records. I need to allow duplicate key entries to update but I do not want to overwrite existing values in the field. I only want to update the fields that are empty. Here is the code as I have it.
    Code:
    $sql="INSERT INTO Results (a, b, c, d, e, f, g, h, i, j)
    VALUES ('$_POST[a]','$_POST[b]','$_POST[c]','$_POST[d]','$_POST[e]','$_POST[f]','$_POST[g]','$_POST[h]','$_POST[i]','$_POST[j]')
    ON DUPLICATE KEY UPDATE f = '$_POST[f]', g = '$_POST[g]', h = '$_POST[h]', i = '$_POST[i]', j = '$_POST[j]'";
    Currently, it does update the field with new information, but it will overwrite existing data with an empty field if it is left empty on update. How can I get it to only update fields that are empty?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You can use the IF function.

    Code:
    UPDATE TableName SET FieldName = IF(Input = '', FieldName, Input)
    Basically this sets FieldName to itself if the input value is a blank string. You said null in your title but leaving a field empty does not always mean it's a null. Most likely a blank string is being passed.

    Comment

    • Kimberly
      New Member
      • Jun 2011
      • 2

      #3
      Thanks so much! Seems so simple now, I just COULD NOT get it. Thank you thank you!

      Comment

      Working...