用 $_POST 索引未定义的 PHP

index undefined php with $_POST

提问人:user2732815 提问时间:8/31/2013 更新时间:8/31/2013 访问量:234

问:

我正在尝试摆脱未定义的索引。每次单击提交而不勾选该框时,我都会收到未定义的索引错误。

<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;
        }
    }
?>
php html post 未定义索引

评论

1赞 Daryl Gill 8/31/2013
也许在所有输入验证中使用?isset

答:

1赞 GautamD31 8/31/2013 #1

尝试点赞isset

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

您也可以改用!=<>

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

评论

0赞 GautamD31 8/31/2013
告诉我是谁打倒这个的原因
1赞 Paul 8/31/2013 #2

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

<?php
if(isset($_POST["submit"]))
{
    if(isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
    {
        $capuccino = 0;
    }
}
?>
0赞 Sankalp Mishra 8/31/2013 #3

您的条件应该是:

if(array_key_exists('cappuccino', $_POST) && isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')
0赞 user2727841 8/31/2013 #4
    <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;
        }
    }
?>