dongyan9950 2014-04-12 13:44
浏览 19
已采纳

问题与数据库中的复选框值...?

I have a settings page as a part of my game for class and one of the settings fields is a checkbox.

This is my HTML field for the checkbox:

<div class="field">
    <label for="allow_robot_name">Allow Robot Name?</label>
    <input type="checkbox" name="allow_robot_name" <?php if ($r->allow_robot_name == 1) { echo "checked"; } ?>>Yes
</div>

The issue I am having is when the user checks the checkbox the value in the database changes to 1. However if they then uncheck it and then update the database the checkbox resets to checked and the value doesn't change from 1 to 0.

This is my code for updating the database:

<?php
$records = array();


if (!empty($_POST)) {
    if (isset($_POST['site_name'], $_POST['header_text'], $_POST['footer_copyright'], $_POST['default_robot_name'])) {

$site_name          = $_POST['site_name'];
$header_text        = $_POST['header_text'];
$footer_copyright   = $_POST['footer_copyright'];
$default_robot_name = $_POST['default_robot_name'];

if (isset($_POST['allow_robot_name'])) {
    $allow_robot_name = 1;
} else {
  $allow_robot_name = 0;
}

if (!empty($site_name) && !empty($header_text) && !empty($footer_copyright) && !empty($allow_robot_name) && !empty($default_robot_name)) {
$update = $db->prepare("UPDATE user_settings set site_name = ?, header_text = ?, footer_copyright = ?, allow_robot_name = ?, default_robot_name = ?");
$update->bind_param('sssis', $site_name, $header_text, $footer_copyright, $allow_robot_name, $default_robot_name);


if ($update->execute()) {
    header('Location: index.php');
    die();
     }
   }
 }
}

Why doesn't the checkbox value update?

  • 写回答

1条回答 默认 最新

  • drfcaw7460 2014-04-12 13:56
    关注

    It's due to !empty($allow_robot_name).

    empty($x) means !isset($x) || $x == null. Since 0 is considered equivalent to null in PHP, empty($allow_robot_name) will evaluate to true, if the checkbox is left unchecked, and your update query is not executed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ 句柄后台鼠标拖动如何实现
  • ¥15 有人会SIRIUS 5.8.0这个软件吗
  • ¥30 comsol仿真等离激元
  • ¥15 静电纺丝煅烧后如何得到柔性纤维
  • ¥15 (标签-react native|关键词-镜像源)
  • ¥100 照片生成3D人脸视频
  • ¥15 伪装视频时长问题修改MP4的时长问题,
  • ¥15 JETSON NANO
  • ¥15 VS开发qt时如何在paintgl函数中用pushbutton控制切换纹理
  • ¥20 关于 openpyxl 处理excel文件地问题