1

I'm using PHP with mysqli and in this example I'm trying to update the price if the username and lastname exists in the database, else I want to insert a new user. Why is this not working?

IF (SELECT name,lastname FROM peoplePrice WHERE name='gus' AND lastname='lw') THEN
    UPDATE peoplePrice SET price='20' WHERE name='gus' AND lastname='lw';
ELSE
    INSERT INTO peoplePrice (name,lastname,price) 
    VALUES ('nisse','johansson','20');
END IF;
5
  • 1
    SELECT returns rows. Have a look at stackoverflow.com/questions/4205181/… Commented Apr 3, 2016 at 21:38
  • try with SELECT COUNT(*) instead Commented Apr 3, 2016 at 21:40
  • Are you just inserting a random user, or should name and lastname match the ones used in the SELECT? Commented Apr 3, 2016 at 21:47
  • you can do the condition checking in php, and then execute the related queries. Commented Apr 3, 2016 at 22:36
  • @wolfsgang This would not be a good idea. If different instances of the script run in parallel, there could be raising conditions resulting in multiple attempts to create rows for the same person. Commented Apr 3, 2016 at 22:46

1 Answer 1

2

MySQL doesn't offer the kind of conditional logic you're using except in stored procedures. You should investigate INSERT ... ON DUPLICATE KEY UPDATE to do what you're trying to do. Read this: http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.