0

Need to stop empty field from submitting and display error message on the same page.

I would appreciate any assistance. Here's the entire shopping cart code. Part in question between lines of asterisks. Thanks!

// If no cart exists, create $_SESSION['cart'] array 
if(!isset($_SESSION['cart'])){
    $_SESSION['cart'] = array();
}

// Add item to array
if(isset($_POST['action']) && $_POST['action'] === 'add'){

/*******************************************************/    
    // Check if input is empty / null
    if(($_POST['id']) == ''){
        $error = '*Please enter an ID number.';
        include 'error.html.php';
        exit();
    }
/*******************************************************/ 

    // Check if form data exists
    if(isset($_POST['id'])){
        $id = $_POST['id'];
    }

    // Check if ID already in cart
    if(isset($_SESSION['cart'][$id])){
        $error = '*Item already in cart.';
    }

    // Add new ID to array (hard-code some data for test file)
    $newitem = array(     
        'id' =>  $id,
        'part_number' =>  '369A7170-11',
        'quantity' =>  '1'
    );

    // Add new data to cart with ID as key    
    $_SESSION['cart'][$id] = $newitem;  
}    

// Remove item from array
if(isset($_POST['action']) && $_POST['action'] === 'remove'){

    // Check if form data exists
    if(isset($_POST['id'])){
        $id = $_POST['id'];
    }

    unset($_SESSION['cart'][$id]);
}

// Empty cart
if(isset($_POST['action']) && $_POST['action'] === 'empty'){
    unset($_SESSION['cart']);
}

// Initialize $count variable; get item count
$count = '';
if(isset($_SESSION['cart'])) $count = count($_SESSION['cart']);

// Display results
if(isset($_SESSION['cart'])){
    $show_cart = var_dump($_SESSION['cart']);
    echo $show_cart;
}


/************** TEST ******************************/
//$_SESSION['quantity'][$id] = $quantity;
if(isset($_SESSION['cart'])) echo 'ID: '  . $_SESSION['cart'][$_POST['id']]['id'] . '<br>';
if(isset($_SESSION['cart'])) echo 'Qty: ' . $_SESSION['cart'][$_POST['id']]['quantity'] . '<br>';
$new_quantity = 5;
if(isset($_SESSION['cart'])) $_SESSION['cart'][$_POST['id']]['quantity'] = $new_quantity;
if(isset($_SESSION['cart'])) echo 'Updated Qty: ' . $_SESSION['cart'][$_POST['id']]['quantity']; 
/************** // END TEST ***********************/

?><!DOCTYPE hml>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Cart</title>
    </head>
<body>
    <h3>Cart Management</h3>
    <p style="color:#ff0000;"><?php if(isset($error)) echo htmlentities($error, ENT_QUOTES); ?></p>
    <p>Items in cart: <?php if(isset($count) && $count > 0)echo htmlentities($count, ENT_QUOTES); else echo 'none'; ?></p>
    <form action="" method="post">
        <label for="id">ID:</label>
        <input type="text" name="id" id="id" autofocus>
        <input type="hidden" name="action" value="add">
        <input type="submit" value="Add">
    </form>

    <form action="" method="post">
        <label for="id">By ID:</label>
        <select name="id" id="id">
            <option value="">Select ID</option>
            <?php foreach($_SESSION['cart'] as $key => $item): ?>
            <option value="<?php echo htmlentities($item['id'], ENT_QUOTES); ?>"><?php echo htmlentities($item['id'], ENT_QUOTES); ?></option>            
            <?php endforeach; ?>
        </select>     
        <input type="hidden" name="action" value="remove">
        <input type="submit" value="Remove"> 
    </form>

    <form action="" method="post">
        <input type="hidden" name="action" value="empty">
        <input onclick="return confirm('Are you sure you want to empty the cart?');" type="submit" value="Empty cart"> 
    </form>
</body>
</html>
JimB814
  • 510
  • 8
  • 24

2 Answers2

2

$_POST['id'] will always be set if it's on your form and it is submitted, regardless if it's empty or not. If you want to check if it's empty, then use

    if(empty($_POST['id'])){
        // give error
    }
    else{
        // do something on success
    }

Alternatively, you could set the input field to be required in the html code. Doing so will make it so the form will not be submitted unless that field has an input.


Try this:

if(isset($_POST['action']) && $_POST['action'] === 'add'){

/*******************************************************/    
// Check if input is empty / null
if(empty($_POST['id'])){
    $error = '*Please enter an ID number.';
}
else{
/*******************************************************/ 

    // Check if form data exists
    if(isset($_POST['id'])){
        $id = $_POST['id'];
    }

    // Check if ID already in cart
    if(isset($_SESSION['cart'][$id])){
        $error = '*Item already in cart.';
    }

    // Add new ID to array (hard-code some data for test file)
    $newitem = array(     
        'id' =>  $id,
        'part_number' =>  '369A7170-11',
        'quantity' =>  '1'
    );

// Add new data to cart with ID as key    
        $_SESSION['cart'][$id] = $newitem;  
    }
}
J. Han
  • 122
  • 1
  • 9
  • Thanks J. Han for your reply. Using the include error page, this works. So does !$_POST['id] . However, without the include error page, which is the solution I want, the empty string submits into the SESSION cart and the error message displays. How do we stop the submission? – JimB814 Sep 02 '15 at 17:02
  • If you put the required tag in the select field, it will force the field to be filed before you can submit the form. – J. Han Sep 02 '15 at 17:15
  • @JimB814, which include error page are you talking about? Can you post that? – J. Han Sep 02 '15 at 17:17
  • Yes. Required works. I will be green checkmarking your answer. But, I prefer not to include error page. Here it is:

    Sorry, error detected.

    ← Go back

    – JimB814 Sep 02 '15 at 17:24
  • The reason why it shows up if you include it is because it's not in your cart page. If you have a div in your cart page for error messages, it would show. I also mentioned the required part in the second part of my answer as both will work. Just move `

    Sorry, error detected.

    ← Go back

    ` somewhere on your cart page and it will work.
    – J. Han Sep 02 '15 at 17:26
  • I did include a spot to display error messages on the cart page. The problem here is that the empty field submits AND the error message displays UNLESS I include an error page. Here's the code that displays the error:

    Maybe I am missing something.
    – JimB814 Sep 02 '15 at 17:32
  • Maybe I'm confused about what you want. Do you want it to submit even with an empty field but it catches it and displays the error and stops? Or do you want it to not submit? I always have this: `
    ` and an error catch for everything that can error out. I do this on the same page without including anything.
    – J. Han Sep 02 '15 at 17:37
  • I do not want it to submit with an empty field. This code triggers an error message that displays precisely where I want near the header of the form, but also submits the data into the SESSION cart. The code I included works if you want to copy it into a text editor. I am baffled why the if statement does not stop the submission. It catches the error because it fires the error message, but yet it lets the data submit. It doesn't make sense. I hope that I am clearly describing the issue. Thanks again for taking your time with this. – JimB814 Sep 02 '15 at 17:44
  • OH! Ok. That's easy to explain. Your if statement doesn't stop everything because it doesn't encompass the ENTIRE functionality. It only prevents this `$id = $_POST['id'];` from occurring. – J. Han Sep 02 '15 at 17:57
  • Ok. But the code a few lines below prevents submission of a duplicate ID and works. Is it the order of the statements? Something is wrong with my code. Here's the lines: // Check if ID already in cart if(isset($_SESSION['cart'][$id])){ $error = '*Item already in cart.'; } – JimB814 Sep 02 '15 at 18:00
  • You need to encompass EVERYTHING from beginning of the check to the end in the if brackets. I will edit my answer to show you what I mean. – J. Han Sep 02 '15 at 18:03
  • Are you saying that after the opening if statement ( === 'add'), place if(isset($_POST['id'])){$id = $_POST['id']; and do not add its closing curly until after $_SESSION['cart'][$id] = $newitem; ? – JimB814 Sep 02 '15 at 18:25
  • Yes. That's exactly. The reason why is because if you don't do that, it only checks if the value is valid when you try to execute $id = $_POST['id']. If it's invalid, it doesn't set $id and continues with the rest of the code. – J. Han Sep 02 '15 at 18:31
  • Did you test it? It doesn't work, unfortunately. It triggers the error message but also goes into the shopping cart. I feel like I am taking up too much of your time. There is something quite peculiar about this. The code here is basic and clear. Everything except this functions. The same functionality works fine 6 lines below this portion. If you want to move on to help others, I understand. I know you're busy. – JimB814 Sep 02 '15 at 18:40
  • Yes, this code works. Except for replacing if($_POST['id'] == ' ') with the if(empty($_POST['id'])), this is exactly the code I had. Now, remove two lines: (1) include 'error.html.php' ; and (2) exit(); This makes it display the error message under the form header exactly as I want, BUT it also submits the empty string into the cart. This is what's bizarre. That the if statement catches the error is proven by two facts: (1) with the include page it works; and (2) without the include page, it triggers the error message near the form. The mystery is that despite error it also submits the data! – JimB814 Sep 02 '15 at 19:39
  • I have a new update. It will check to see if the value is empty. If it is, it'll skip the adding. If it isn't empty, it'll add ot the cart. – J. Han Sep 02 '15 at 19:41
  • Here is a solution: [http://stackoverflow.com/questions/23954757/update-value-in-session-array-php] from Ahmad [http://stackoverflow.com/users/1919959/ahmad] – JimB814 Sep 03 '15 at 12:24
0

Use the following syntax instead and it should work.

if(!$_POST['id']){ 
    code....
}
Erik Flitman
  • 163
  • 4
  • Thanks Erik. This works with the include page, but without it, it submits the empty field and displays the error message. We're halfway there. Is there a way to stop the submission? – JimB814 Sep 02 '15 at 17:07
  • I wasn't clear what you were asking. So the form is already submitted by the client once php gets a hold of it so in this case you will want to exit the continuation with the script and not process any db updates or whatever you are going to do. If you want form validation before actually submitting the form, then you would want to use javascript to validate the form data before the actual submission. – Erik Flitman Sep 02 '15 at 18:01
  • Thanks Erik. The if statement catches the error because when I include an error page it works. When I eliminate the error page so that the error displays near the form header, the messages does display, but the empty field also submits. That is the baffling part. Code just below this part does the same thing and works fine. It displays an error message and everything stops. With this part, however, the error is seen and YET the code continues and it deposits an empty field into the cart. Frustrating. – JimB814 Sep 02 '15 at 18:06
  • Here is a solution: [http://stackoverflow.com/questions/23954757/update-value-in-session-array-php] from Ahmad [http://stackoverflow.com/users/1919959/ahmad] – JimB814 Sep 03 '15 at 12:25