使用$_POST索引未定义的php


index undefined php with $_POST

我正在尝试清除未定义的索引。每次我点击提交而不勾选框,我都会得到一个未定义的索引错误。

<html>
    <head>
        <title>Order</Title>
            <style>
            </style>
        <body>
            <form action = "order.php" method = "post">
                Coffee:<p>
                <input type = "checkbox" value = "coffee" name = "cappuccino"/>Capuccino<br>
</form>
        </body> 
    </head>
</Html>
<?php
    $capuccino = 3.75;
    if(isset($_POST["submit"]))
    {
        if($_POST['cappuccino'] <> 'coffee')
        {
            $capuccino = 0;
        }
    }
?>

尝试使用类似的isset

<?php
    if(isset($_POST["submit"]))
    {
        if(isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
        {
            $capuccino = 0;
        }
    }
?>

您也可以使用!=代替<>

$_POST['cappuccino'] != 'coffee'

在HTML表单中,如果你不检查值,它就不会被发布。你应该先测试它是否被发布,所以你的php代码应该是这样的:

<?php
if(isset($_POST["submit"]))
{
    if(isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
    {
        $capuccino = 0;
    }
}
?>

您的条件应该是:

if(array_key_exists('cappuccino', $_POST) && isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
    <html>
    <head>
        <title>Order</Title>
            <style>
            </style>
        <body>
            <form action = "order.php" method = "post">
                Coffee:<p>
                <input type = "checkbox" value = "coffee" name = "cappuccino"/>Capuccino<br>
<input type="submit" name="submit" value="Submit" />
</form>
        </body> 
    </head>
</Html>
<?php
    $capuccino = 3.75;
    if(isset($_POST["submit"]))
    {
        if(isset($_POST['cappuccino']) && !empty($_POST['cappuccino']) <> 'coffee')
        {
            $capuccino = 0;
        }
    }
?>