0

I made a script that auto creates Update statement using For loops and all and the final result executes this:

mysql_query("UPDATE table2 
              SET(code2='sfvv' WHERE number='1'),
                 (code2='sdvsdv' WHERE number='2') 
              WHERE id='32'") or die ( mysql_error() );

The error said: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(code2='sfvv' WHERE number='1'),(code2='sdvsdv' WHERE number='2') WHERE i' at line 1

3 Answers 3

2

I guess you need case statement

UPDATE table2 
SET code2= case number when 1 then 'sfvv' when 2 then 'sdvsdv' END
where id = 32
Sign up to request clarification or add additional context in comments.

1 Comment

It worked for my case I finally got it working , thankyou , I learned something new :)
2

You use AND and OR statements to combine conditions:

UPDATE table2
SET code2 = 'sfvv'
WHERE
    (number = '1'AND code2 = 'sdvsdv')
    OR
    (number = '2' AND id = '32')

You can update multiple values in the same row by using commas to separate the statements:

UPDATE table2
SET code2 = 'sfvv', code3 = 'abc'

If you need to update different rows based on different conditions, you need to execute multiple queries:

UPDATE table2 SET code2 = 'sfvv' WHERE id = 1;
UPDATE table2 SET code3 = 'abc' WHERE id = 2;

As the other answer mentioned, you can also use case statements in your SET clause:

UPDATE table2
SET code2 = CASE WHEN number = 1 THEN 'foo' ELSE 'bar' END

But this is not 100% flexible. Use it when it makes sense.

4 Comments

You use AND and OR statements to combine conditions: Possibly you should use an OR in your first sql statement as currently that wont do anything unless number can be 1 AND 2 at the same time???
Number 1 and 2 are different rows and they are 1,2 they are updated to the given code2 which both are null
@RiggsFolly Thanks, was too focused on formatting the code.
ThankYou Both For Trying It Reminded me that I can still use OR & AND in situations like these ;)
1
Update  table2 
     SET code2= CASE 
                 WHEN  number=1 THEN 'sfvv'
                 WHEN  number=2 THEN 'sdvsdv'
                 ELSE  code2
                 END 
     WHERE id = 32

Hope it helps

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.