Zaki Aziz
Zaki Aziz

Reputation: 3852

Update a columns if certain value

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

Upvotes: 3

Views: 6632

Answers (3)

Barry Chapman
Barry Chapman

Reputation: 6780

Why not just do an update with conditions?

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

That should do what you are looking for

Upvotes: 3

Rudiger
Rudiger

Reputation: 6769

UPDATE tableName SET columnA = 2 WHERE columnA = 1

Upvotes: 3

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

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 :)

Upvotes: 12

Related Questions