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')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度