我是PHP和MySql的新手,我已经在互联网上搜索过但无法找到合适的答案。
使用PHP,我需要从MySQL数据库的单个单元格中获取值,并检查该值是否等于0或1.如果它等于1,则将其设置为0,反之亦然
我该怎么办?谢谢你的帮助!!
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql_light = mysqli_query("SELECT light FROM bot_command WHERE cmd_id = '1'");
$result_light = mysql_fetch_assoc($sql_light);
if (isset($result_light['light']) && $row['light'] == 1) {
$sql = "UPDATE bot_command SET light='0' WHERE cmd_id = '1'";
$result = $conn->query($sql);
// output data of each row
while($row = $result_select->fetch_assoc()) {
echo " - Light: " . $row["light"]."<br>";
}
} else {
echo "0 results";
}
if ($conn->query($sql) === TRUE) {
echo " - Record updated successfully";
} else {
echo " - Error updating record: " . $conn->error;
}
$conn->close();
//$sql = "SELECT light FROM bot_command WHERE cmd_id = '1'";
?>
答案 0 :(得分:3)
在一个查询中有一个老技巧:
UPDATE `tablename` SET `field` = 1 - `field`
这种情况如果field == 1
它将变为0
,如果它是0
,它将成为1
答案 1 :(得分:1)
使用MySQL的IF
:
UPDATE bot_command
SET light=IF( light=1, 0, 1)
WHERE cmd_id = '1';
答案 2 :(得分:0)
你应该这样写:
$sql_light = mysqli_query($con,"SELECT light FROM bot_command WHERE cmd_id = '1'");
if(mysqli_num_rows($sql_light)>0){
$result_light = mysqli_fetch_assoc($sql_light);
if($result_light['light']=="0"){
$sql = "UPDATE bot_command SET light='1' WHERE cmd_id = '1'";
}else{
$sql = "UPDATE bot_command SET light='0' WHERE cmd_id = '1'";
}
$result = mysqli_query($sql);
if($result){
echo "Updated..";
}else{
echo "Not Updated..";
}
}
答案 3 :(得分:0)
UPDATE table SET value = ABS(value - 1)
简单而有效。
这会将所有1
更改为:1 - 1 = 0
,将所有0
更改为绝对值:0 - 1 = -1
,ABS(-1) = 1