user2732815
user2732815

Reputation: 55

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

Upvotes: 0

Views: 234

Answers (4)

user2727841
user2727841

Reputation: 725

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

Upvotes: 0

William Buttlicker
William Buttlicker

Reputation: 6000

You condition should be:

if(array_key_exists('cappuccino', $_POST) && isset($_POST['cappuccino']) && $_POST['cappuccino'] <> 'coffee')

Upvotes: 0

Paul
Paul

Reputation: 471

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

Upvotes: 1

GautamD31
GautamD31

Reputation: 28763

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'

Upvotes: 1

Related Questions