dqzg62440 2013-10-09 00:58
浏览 47
已采纳

用于更新值的PHP脚本无法正常工作

I have the following PHP script that I am trying to execute. Its very simple yet I am overlooking something since it is not working correctly. If a user toggles a radio button, this script is called and the page is refreshed. However, the "enabled" column in MySQL never updates going from "0" to "1". If I manually enter the value of the enabled column to "1" then the script executes updating the value of the enabled column back to "0" but never to "1" again. What am I overlooking?

$sql="SELECT enabled FROM somecolumn.persist";
$row = mysql_fetch_row($sql);
$enabled=$row[0];

if ($enabled==0) {
    $query="UPDATE `somecolumn`.`persist` SET  `enabled` =  '1' WHERE `persist`.`enabled` =0";
} else {
    $query="UPDATE `somecolumn`.`persist` SET  `enabled` =  '0' WHERE `persist`.`enabled` =1";
}
mysql_query($query);
  • 写回答

2条回答 默认 最新

  • duanpao4522 2013-10-09 01:15
    关注

    It seems like all you are doing is toggling the column value for all records in the given table. Why even bother reading the value from the database and then doing an update? You can simply do an update right off the bat.

    $sql = "UPDATE `somecolumn`.`persist` SET `enabled` = ABS(`enabled` - 1)";
    $result = mysql_query($sql);
    
    if (false === $result) { // something went wrong
        throw new Exception('Query "'. $sql . '" failed with error: ' . mysql_error());
    }
    

    This would flip all 1's to 0's and 0's to 1' without having to do any SELECT at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据