I'm having some difficulty putting a conditional into MySQL. I've been trying to create a query that will go through all of the column titled email and if it exists I want to do something like this:
If an email exists I want it to take the existing value of the column correct and add the php variable $correct to it. But if an email does not exist then I want it to add a new record with the values $email into the column email and $correct into column correct. Any help would be greatly appreciated.
Here's what I have and does not work:
IF (SELECT * FROM facebookqs WHERE email = '$email' > 0)
UPDATE facebookqs SET correct = correct + '$correct' where email ='$email'
Else
Insert into facebookqs (email, correct) VALUES ('$email', '$correct')
Assuming
email
has aUNIQUE
constraint, you should use INSERT ... ON DUPLICATE KEY UPDATESee also my answer for this other Stack Overflow question: INSERT IGNORE vs INSERT … ON DUPLICATE KEY UPDATE
Do you need to select the e-mail column only? Or do you have multiple columns that contain e-mail addresses? If you have multiple columns with email then you would need to say where col1Email = '$email' or col2Email='$email'... etc. To get a count of the rows try SELECT COUNT(*) from facebookqs where col1Email = '$email' or col2Email='$email'.
Use the
REPLACE
method, explained here: http://blogs.coldbuffer.com/inserting-or-updating-records-using-mysql-replace From their example:which given your example should be (haven't tested it yet)
Your missing an
EXISTS
statement and theTHEN
andEND IF
in theIF