doushengyou2617 2015-08-09 19:31
浏览 107
已采纳

在PHP中将字段值限制为1或0

I am trying to restrict the value entered for the form field 'active' to either 0 or 1, 0 being inactive and 1 being active

The code that is inserting the user in the database:

if ($_POST['active'] != '1' || $_POST['active'] != '0') {
    $errors[] = 'Active field can only take values of either 1 or 0';
} else {
        if (empty($_POST) === false && empty($errors) === true) {
            $register_data = array(
                'username'      => $_POST['username'],
                'password'      => $_POST['password'],
                'first_name'    => $_POST['first_name'],
                'email'         => $_POST['email'],
                'active'        => $_POST['active'],
                );
            admin_add_user($register_data);
            header('Location: add_user.php?success');
            exit();
        } 
        else if (empty($errors) === false) {
            echo output_errors($errors);
        }
}

The function:

function admin_add_user($register_data) {
    include('core/db/db_connection.php');
    array_walk($register_data, 'array_sanitize'); 
    $register_data['password'] = md5($register_data['password']);
    $fields = '`' . implode('`, `', array_keys($register_data)) . '`'; 
    $data = '\'' . implode('\', \'', $register_data) . '\''; 
    $sql = "INSERT INTO `_users` ($fields) VALUES ($data)";
    $query = mysqli_query($dbCon, $sql);
}

How can I restrict the values entered for the form field named 'active' to 1 or 0? I have tried 1 and 0 without the apostrophes but I still get the error associated with this if statement.

  • 写回答

1条回答 默认 最新

  • duanji1482 2015-08-09 19:33
    关注

    There's a problem with your condition. Use && instead of ||:

    if ($_POST['active'] != '1' && $_POST['active'] != '0')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集