是php-mysql:根据涉及PHP变量的条件,使用不同的值更新列

时间:2019-02-26 20:16:11

标签: php mysql if-statement mysqli sql-update

我有一个网络表单,其中的字符串变量为$participant1, participant2和php中的$winner。发布表单后,它将更新两行中的participantwinnermy_tablewinner的列类型为BOOLEAN

这是我的桌子目前的样子:

ID |Game |Participant | Winner
-------------------------------
1     1     John          NULL
2     1     Frank         NULL

提交的变量$winner将是participant的名称(“ John”或“ Frank”)。提交后,我希望设置1与字符串$winner匹配的参与者。还有0代表其他参与者。

即如果$participant1 =='John' and $winner=='John' 然后该表应如下所示:

ID |Game |Participant | Winner
-------------------------------
1     1     John          1
2     1     Frank         0

我似乎无法弄清楚这部分。

我尝试过:

$participant1= mysqli_escape_string( $con, $params['participant1']);
$participant2= mysqli_escape_string( $con, $params['participant2']);
$Winner= mysqli_escape_string( $con, $params['Winner']);    

mysqli_query($con, "UPDATE my_table SET Winner = IF('$Winner'=='$participant1',1,0) WHERE Participant ='$participant1');

mysqli_query($con, "UPDATE my_table SET Winner = IF('$Winner'=='$participant2',1,0) WHERE Participant ='$participant2'");
之后

Winner仍显示NULL。有没有主要的MySQL方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

嘿,用=替换==

mysqli_query($con, "UPDATE my_table SET Winner = IF('$Winner'='$participant1',1,0) WHERE Participant ='$participant1'");

经过测试的代码:

$mysqli = new mysqli("localhost", "root", "", "test");
$a='John';
$b='Mary';

$w='John';

mysqli_query($mysqli, "UPDATE myguest SET Winner = IF('$a'='$w',1,0) WHERE FirstName ='$a'");
mysqli_query($mysqli, "UPDATE myguest SET Winner = IF('$b'='$w',1,0) WHERE FirstName ='$b'");