If I have a table with 3 columns: id,column1,column2. If i want to update column1 just when receiving "column1" parameter in URL request otherwise update column2 when receiving "column2" parameter in URL adress. Is that possible? I made that but i think that's not correct:
$sql= "UPDATE people SET
answer_yes= '$answer_yes'+1,
answer_no='$answer_no'+1";
Thank you for helping.
EDIT: Now that is working (based on Richard Vivian answer)
If($answer_yes==1)
{
$sql= "UPDATE people SET answer_yes= answer_yes +1"or die(mysql_error());
mysql_query($sql);
}
else if ($answer_no==0)
{
$sql= "UPDATE people SET answer_no= answer_no+1" or die(mysql_error());
mysql_query($sql);
}
You can create 2 SQL statement options:
If($answer_yes)
{
$sql= "UPDATE people SET answer_yes= '$answer_yes'+1"
}
else
{
$sql= "UPDATE people SET answer_no= '$answer_no'+1"
}
You can do this:
UPDATE people
SET answer_yes = COALESCE($answer_yes + 1, answer_yes),
answer_no = COALESCE($answer_no + 1, answer_no);
The COALESCE
returns the first non NULL
able value in the values passed to it. If any of the parameters $answer_yes
or $answer_no
were passed with a NULL
value, then $answer_yes + 1
and $answer_no + 1
will be evaluated to NULL
also, there for the COALESCE
will return the column value, and in this case the column will be updated with its value, i.e, it won't changed.
I'm unsure which database model you are using, but the logic would be to pass a NULL
value if you don't have a value to pass, and check that the values not null before updating.
SQL Server
UPDATE Table
SET Column1=ISNULL(@Column1,Column1),
Column2=ISNULL(@Column2,Column2)
MySQL
UPDATE Table
SET Column1=IFNULL($Column1,Column1),
Column2=IFNULL($Column2,Column2)
What is happening here is that ISNULL/IFNULL
is checking whether the first value passed to it is NULL
, and if it is, its returning the 2nd value. The 2nd value is the same value as the current value, and therefore it updates it with the same value (ie. Not changing the value).