3

I have a certain column in a table that stores a number. I want this number to be set to 2 ONLY if it previously equaled 1. I was wondering if it was possible to avoid this:

$val = mysql_fetch_row(mysql_query("SELECT columnA FROM tableName WHERE something = '$someValue'"));

if($val[0] == 1) { .....UPDATE tableName SET columnA = 2....... }

Is it possible to directly query the database? With something like this:

SET columnA = 2 if columnA = 1
1
  • 1
    There is really no need to bring PHP logic into this, just do it all in one MySQL UPDATE statement as seen below Commented Feb 8, 2012 at 6:58

3 Answers 3

12

Actually the query you're looking for should be:

update tableName set columnA = 2
where columnA = 1

The "if" you're mentioning is actually a condition. And these conditions are set in the where clause of the update statement.

That's it :)

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

Comments

3
UPDATE tableName SET columnA = 2 WHERE columnA = 1

Comments

3

Why not just do an update with conditions?

UPDATE tableName SET columnA = '2' WHERE columnA = '1'

That should do what you are looking for

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.