简体   繁体   中英

index undefined php with $_POST

I am trying to get rid of the index undefined. Every time I click submit without ticking the box, I get an undefined index error.

<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;
        }
    }
?>

Try with isset like

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

You can also use != instead <>

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

In HTML forms, a value does not get posted if you do not check it. You should test if it was posted first, so your php code would be something like:

<?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;
        }
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM