从单选按钮获取输入到php,然后添加到数据库

5uzkadbs  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(403)

mysql数据库中的mytableusers有一个列角色声明为enum,这意味着用户将是投资者或经理。所以在php页面中,我需要使用单选按钮进行输入
代码如下

<div class="form-group <?php echo (!empty($role_err)) ? 'has-error' : ''; ?>">
    <label>ROLE </label>
    <form action="" method="post">
        <input type="radio" name="role" value="<php echo $role; ?>">INVESTOR
        <input type="radio" name="role" value="<php echo $role; ?>">MANAGER
        <span class="help-block"><?php echo $role_err;?></span>
</div>

验证代码如下

if($_POST["role"])
{
    $input_role = trim($_POST["role"]);
    if(empty($input_role)){
        $role_err = "Please enter a proper role.";     
    } else{
        $role = $input_role;
    }
}

我对整个表使用的sql查询是

// Check input errors before inserting in database
if(empty($username_err) && empty($fullname_err) && empty($age_err) && empty($phonenumber_err) && empty($role_err)){
    // Prepare an insert statement
    $sql = "INSERT INTO users (user_name, full_name, age, phone_number, role) VALUES (?, ?, ?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
        // Bind variables to the prepared statement as parameters
        mysqli_stmt_bind_param($stmt, "ssiis", $param_username, $param_fullname, $param_age, $param_phonenumber, $param_role);

        // Set parameters
        $param_username = $username;
        $param_fullname = $fullname;
        $param_age = $age;
        $param_phonenumber = $phonenumber;
        $param_role = $role;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt)){
            echo "Records created successfully. Redirect to landing page";
            // Records created successfully. Redirect to landing page
            header("location: index.php");
            exit();
        } else{
            echo "Something went wrong. Please try again later.";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);
}

// Close connection
mysqli_close($link);
}

即使在这之后,角色也被添加为null;

zaqlnxep

zaqlnxep1#

试试这个,应该可以:

<div class="form-group <?php echo (!empty($role_err)) ? 'has-error' : ''; ?>">
    <label>ROLE </label>
    <form action="" method="post">
    <input type="radio" name="role"
    <?php if (isset($role) && $role=="INVESTOR") echo "checked"; value="INVESTOR">INVESTOR
    <input type="radio" name="role"
    <?php if (isset($role) && $role=="MANAGER") echo "checked";?value="MANAGER">MANAGER
    <span class="help-block"><?php echo $role_err;?></span>
</div>

相关问题