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

报告相同问题?