如何使用PHP将单选按钮的选择存储在变量中


How to stored the selection of a radio button in a variable with PHP

我正试图将从PHP的单选选项中选择的值引入一个变量中,以便使用该值。

一旦用户从我的收音机中选择了一个选项(有5个选项:1到5),我试图通过PHP将值存储在变量$rating中,然后我尝试打印变量的值两次,一次是在我的PHP代码中使用

echo $rating;

还有一次在我的HTML中使用

<?php echo $rating;?>

但这两种情况都不打印,所以我猜我无法存储价值。

如有任何帮助,我们将不胜感激。

<html>
<body>
    <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
          $rating =  "";
          $rating = $_POST['rating'];
          echo $rating;
        <input type="radio" name="rating" value="1">
        <input type="radio" name="rating" value="2">
        <input type="radio" name="rating" value="3">
        <input type="radio" name="rating" value="4">
        <input type="radio" name="rating" value="5">
        <br>
        <?php echo $rating;?>
</body>
</html>

花几分钟时间帮助您

正如我在评论中提到的,您需要<form></form>标记来处理POST数组和POST方法。

下面使用了PHP的三元运算符(它更干净)和isset()

<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
    <?php
      if ($_SERVER["REQUEST_METHOD"] == "POST") {
          $rating = $_POST['rating'];
}
?>
<?php 
$choice = "You chose: ";
    echo isset($rating) ? $choice.$rating : 'Make a selection';
?>
<form method = "post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
        <input type="radio" name="rating" value="1">
        <input type="radio" name="rating" value="2">
        <input type="radio" name="rating" value="3">
        <input type="radio" name="rating" value="4">
        <input type="radio" name="rating" value="5">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

参考文献:

  • http://php.net/manual/en/language.operators.comparison.php
  • http://php.net/manual/en/function.isset.php
  • http://php.net/manual/en/tutorial.forms.php

您的代码似乎不完整。尽管您正在检查POST请求方法,但并没有通过POST方法发布数据的表单。

<html>
<body>
    <?php
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $rating =  "";
        $rating = $_POST['rating'];
        echo $rating;
    }
    else{
    ?>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"
        <input type="radio" name="rating" value="1">
        <input type="radio" name="rating" value="2">
        <input type="radio" name="rating" value="3">
        <input type="radio" name="rating" value="4">
        <input type="radio" name="rating" value="5">
        <input type="submit" name="submit">
        <br>
    </form>
    <?php } //end of 'if' statement ?>
</body>
</html>

供html表单参考