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

时间:2015-08-09 19:31:25

标签: php

我正在尝试限制为表单字段输入的值' active' 0或1,0表示不活动,1表示活动

将用户插入数据库的代码:

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);
        }
}

功能:

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);
}

如何限制为名为' active'的表单字段输入的值到1还是0?我已经尝试了1和0没有撇号,但我仍然得到与此if语句相关的错误。

1 个答案:

答案 0 :(得分:1)

你的病情有问题。使用&&代替||

if ($_POST['active'] != '1' && $_POST['active'] != '0')