如何在PHP中插入多个HTML清单值?

时间:2018-09-05 10:51:27

标签: php html forms input

我正在尝试在if-else条件下插入多个清单值。即使我检查多个值,我似乎也只能在条件中插入一个值。我的代码是:

<?php

    $db_host = 'localhost'; // Server Name
    $db_user = 'root'; // Username
    $db_pass = ''; // Password
    $db_name = 'assign'; // Database Name

    $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
    if (!$conn) {
        die ('Failed to connect to MySQL: ' . mysqli_connect_error());  
    }
?>


<html>

<body>
    <div class="form-style-8">
    <center><h2>Make a Choice</h2></center>
    <form action="#" method="post">
    <input type="checkbox" name="choice[]" value="bat">Batting</input>
    <input type="checkbox" name="choice[]" value="bwl">Bowling</input>
    <input type="checkbox" name="choice[]" value="fld">Fielding</input>
    <input type="submit" name="submit" value="Submit"/>
    </form>
    </div>
</body>


<?php
    if(isset($_POST['submit'])){
        if(!empty($_POST['choice'])){
            foreach($_POST['choice'] as $selected){
                if($selected == "bat"){
                    header('Location: Batting.php');
                }
                else if($selected == "bwl"){
                    header('Location: Bowling.php');
                }
                else if($selected == "fld"){
                    header('Location: Fielding.php');
                }
                else if($selected == "batbwl" || $selected == "bwlbat"){
                    header('Location: BatBwl.php');
                }
            }
        }
    }
?>

</html>

正如您所看到的,我试图将所有值都统一为“ batbwl”,因为如果执行“ echo $ selected”,这就是回声。但它只会传递bwl到条件上。谁能帮我解决这个问题?

1 个答案:

答案 0 :(得分:-1)

请勿用于此类情况。 试试这个

<html>

<body>
    <div class="form-style-8">
    <center><h2>Make a Choice</h2></center>
    <form action="#" method="post">
    <input type="checkbox" name="choice[]" value="bat">Batting</input>
    <input type="checkbox" name="choice[]" value="bwl">Bowling</input>
    <input type="checkbox" name="choice[]" value="fld">Fielding</input>
    <input type="submit" name="submit" value="Submit"/>
    </form>
    </div>
</body>


<?php
    if(isset($_POST['submit'])){
        if(!empty($_POST['choice'])){
                if((@$_POST['choice'][0] == "bat") && (@$_POST['choice'][1] == "bwl")){
                    header('Location: BatBwl.php');
                }
                else if($_POST['choice'][0] == "bwl"){
                    header('Location: Bowling.php');
                }
                else if($_POST['choice'][0] == "fld"){
                    header('Location: Fielding.php');
                }
                else if($_POST['choice'][0] == "bat"){
                    header('Location: Batting.php');
                }
        }
    }
?>

</html>