1

I'm almost finished with my first college PHP assignment. It's been a headache but I'm in the homestretch. The problem I'm having now is with validation. I have validated that the input boxes contain appropriate data. The instructions tell me to make certain that if the user hits the "confirm" button with no data entered, the user will be redirected back to the index.php (the same page). Right now the user can click "confirm" and, even if the input boxes are empty, it will direct them to the next page. I've tried multiple ways with no success. I've commented out the latest attempt. I'm confused by a lot of the examples I've finding online because they also include validation that I've already done. I'm also finding a lot of examples that use JavaScript. I must use PHP for all validation. Help will be very much appreciated.

I have updated my code now that I have it working. But another issue has been created. The error messages are appearing next to the input boxes before data is even entered .. rather than appearing after submitting the page with missing or inaccurate data.

<?php

/*
 * Course : Server-Side Programming
 * Student: Sherrie Teague
 * Assignment: HW2 - Quote
 * Date : 2/6/2019
*/

// get the data from the form
$sales_price = filter_input(INPUT_POST,'sales_price', FILTER_VALIDATE_FLOAT);
$discount_percent = filter_input(INPUT_POST,'discount_percent',FILTER_VALIDATE_FLOAT);
$total_price = filter_input(INPUT_POST,'total_price', FILTER_VALIDATE_FLOAT);


/*// validate sales_price
if ($sales_price === FALSE) {
    $sales_priceError = 'Sales price must be a valid amount';
} else if ($sales_price < 1.0) {
    $sales_priceError = 'Sales price must be greater than 0';
} else {
    $sales_priceError = '';
}

// validate discount_percent
if ($discount_percent === FALSE) {
    $discount_percentError = 'Discount percent must be a valid amount';
} else if ($discount_percent < 1.0) {
    $discount_percentError = 'Discount percent must be greater than 0';
} else {
    $discount_percentError = '';
}*/


if( isset( $_POST['confirmSubmit'] )) {
    echo 'Validation Error';
    // or store it in a variable and post later
    $validation_error = 'Validation Error';
}

$sales_valid = true;
$sales_priceError = '';
if ($sales_price === FALSE) {
    $sales_priceError = 'Sales price must be a valid amount';
    $sales_valid = false;
} else if ($sales_price < 1.0) {
    $sales_priceError = 'Sales price must be greater than 0';
    $sales_valid = false;
}

$discount_valid = true;
$discount_percentError = '';
// validate discount_percent
if ($discount_percent === FALSE) {
    $discount_percentError = 'Discount percent must be a valid amount';
    $discount_valid = false;
} else if ($discount_percent < 1.0) {
    $discount_percentError = 'Discount percent must be greater than 0';
    $discount_valid = false;
}


// calculate the discount and the discounted price
$discount_amount = $sales_price * $discount_percent / 100;
$total_price = $sales_price - $discount_amount;

?>

<!doctype html>
<html lang="en">
<head>
    <title>Quote</title>
    <link rel="stylesheet" type="text/css" href="quote.css">
</head>
<body>
<section>
    <h1>Price Quotation</h1>
    <form id="priceForm" name="priceForm" method="post" action=''>
        <label for="sales_price">Sales Price </label>
        <input type="text" id="sales_price" name="sales_price" required
               value="<?php echo $sales_price; ?>"/>
        <?php if (!empty($sales_priceError)) : ?>
            <span style="color:red;background-color: white">
                    <?php echo $sales_priceError; ?>
            </span>
        <?php endif; ?>
        <br/>
        <br/>
        <label for="discount_percent">Discount Percent </label>
        <input type="text" id="discount_percent" name="discount_percent" required
               value="<?php echo $discount_percent; ?>"/>
        <?php if (!empty($discount_percentError)) : ?>
            <span style="color:red;background-color: white">
                    <?php echo $discount_percentError; ?>
                </span>
        <?php endif; ?>
        <p class="discount">Discount Amount <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($discount_amount, 2); ?></p>
        <p class="total">Total Price <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($total_price, 2); ?></p>
        <input type="submit" class=inline name="submitButton" id="submitButton" value="Calculate"/>
    </form>

<!--     <form id="confirmForm" name="confirmForm" method="post" action="confirm.php">-->
         <form id="confirmForm" name="confirmForm" method="post" action="<?php echo ( ( $sales_valid && $discount_valid ) ? 'confirm.php' : '' ); ?>">
            <input type="hidden" id="sales_price" name="sales_price" value="<?php echo $sales_price ?>" />
            <input type="hidden" id="discount_amount" name="discount_amount" value="<?php echo $discount_amount ?>"/>
            <input type="hidden" id="total_price" name="total_price" value="<?php echo $total_price ?>"/>
            <input type="submit" class= inline name="confirmSubmit" id="confirmSubmit" value="Confirm"/>
     </form>

    <div>
        <p> Enter price and discount amount and click Calculate</p>
    </div>
</section>
</body>
</html>
Vienne
  • 101
  • 6

3 Answers3

1

You could do something like:

if( isset( $_POST['confirmSubmit'] ) ) {
   echo 'Validation Error';
  // or store it in a variable and post later
   $validation_error = 'Validation Error';
}

$sales_valid = true;
$sales_priceError = '';
if ($sales_price === FALSE) {
    $sales_priceError = 'Sales price must be a valid amount';
    $sales_valid = false;
} else if ($sales_price < 1.0) {
    $sales_priceError = 'Sales price must be greater than 0';
    $sales_valid = false;
}

$discount_valid = true;
$discount_percentError = '';
// validate discount_percent
if ($discount_percent === FALSE) {
    $discount_percentError = 'Discount percent must be a valid amount';
    $discount_valid = false;
} else if ($discount_percent < 1.0) {
    $discount_percentError = 'Discount percent must be greater than 0';
    $discount_valid = false;
}

And then for your form update it to:

<form id="confirmForm" name="confirmForm" method="post" action="<?php echo ( ( $sales_valid && $discount_valid ) ? 'confirm.php' : '' ); ?>">

This will echo if confirm.php into the action if both $sales_valid and $discount_valid are true, otherwise it will return blank which will refresh the page.

EDIT-------------------- I'd run my code similar to this, although could still be optimized to run better:

   <?php

// set default values
$sales_price = '';
$sales_valid = true;
$sales_priceError = '';

$discount_percent = '';
$discount_valid = true;
$discount_percentError = '';

$discount_amount = 0;
$total_price = 0;

$validation_error = '';

// check for validation error submit
if( isset( $_POST['confirmSubmit'] ) ) {
   $validation_error = 'Validation Error';
   $discount_valid = false;
   $sales_valid = false;
}
// check for submit 
if( isset( $_POST['submitButton'] ) ) {

    $sales_price = filter_input(INPUT_POST,'sales_price', FILTER_VALIDATE_FLOAT);
    $discount_percent = filter_input(INPUT_POST,'discount_percent',FILTER_VALIDATE_FLOAT);
    $total_price = filter_input(INPUT_POST,'total_price', FILTER_VALIDATE_FLOAT);

    if ($sales_price === FALSE || $sales_price == '') {
        $sales_priceError = 'Sales price must be a valid amount';
        $sales_valid = false;
    } else if ($sales_price < 1.0) {
        $sales_priceError = 'Sales price must be greater than 0';
        $sales_valid = false;
    }

    // validate discount_percent
    if ($discount_percent === FALSE || $discount_percent == '') {
        $discount_percentError = 'Discount percent must be a valid amount';
        $discount_valid = false;
    } else if ($discount_percent < 1.0) {
        $discount_percentError = 'Discount percent must be greater than 0';
        $discount_valid = false;
    }

    // calculate the discount and the discounted price
    $discount_amount = $sales_price * $discount_percent / 100;
    $total_price = $sales_price - $discount_amount;
}    


?>

<!doctype html>
<html lang="en">
<head>
    <title>Quote</title>
    <link rel="stylesheet" type="text/css" href="quote.css">
</head>
<body>
<section>
    <h1>Price Quotation</h1>
    <form id="priceForm" name="priceForm" method="post" action=''>
        <label for="sales_price">Sales Price </label>
        <input type="text" id="sales_price" name="sales_price" value="<?php echo $sales_price; ?>" required />

        <?php

        if ( ! empty($sales_priceError) ) { ?>
            <span style="color:red;background-color: white">
                    <?php echo $sales_priceError; ?>
            </span>
        <?php } ?>
        <br/>
        <br/>
        <label for="discount_percent">Discount Percent </label>
        <input type="text" id="discount_percent" name="discount_percent" value="<?php echo $discount_percent; ?>" required"/>

        <?php if (!empty($discount_percentError)) : ?>
            <span style="color:red;background-color: white">
                    <?php echo $discount_percentError; ?>
                </span>
        <?php endif; ?>
        <p class="discount">Discount Amount <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($discount_amount, 2); ?></p>
        <p class="total">Total Price <?php echo '&nbsp;&nbsp;&nbsp;&nbsp;$' . number_format($total_price, 2); ?></p>
        <input type="submit" class=inline name="submitButton" id="submitButton" value="Calculate"/>
    </form>
    <form id="confirmForm" name="confirmForm" method="post" action="<?php echo ( ( isset( $_POST['confirmSubmit']) && $sales_valid && $discount_valid ) ? 'confirm.php' : '' ); ?>">
            <input type="hidden" id="sales_price" name="sales_price" value="<?php echo $sales_price ?>" />
            <input type="hidden" id="discount_amount" name="discount_amount" value="<?php echo $discount_amount ?>"/>
            <input type="hidden" id="total_price" name="total_price" value="<?php echo $total_price ?>"/>
            <input type="submit" class= inline name="confirmSubmit" id="confirmSubmit" value="Confirm"/>
     </form>

    <div>
        <p> Enter price and discount amount and click Calculate</p>
    </div>
</section>
</body>
</html>
Second2None
  • 1,470
  • 1
  • 12
  • 22
  • thank you! This is working but I'm getting error messages on my page.. Telling me that there are undefined variables .. on lines 18, 21, 29, and 32. The variables are $sales_price and $discount_percent – Vienne Feb 06 '19 at 05:30
  • 1
    Need to make sure you are including the rest of your code: `$sales_price = filter_input(INPUT_POST,'sales_price', FILTER_VALIDATE_FLOAT); $discount_percent = filter_input(INPUT_POST,'discount_percent',FILTER_VALIDATE_FLOAT); $total_price = filter_input(INPUT_POST,'total_price', FILTER_VALIDATE_FLOAT);` – Second2None Feb 06 '19 at 05:34
  • Forgive my previous comment. I only needed to paste the code beneath where I named the variables. Thank you so very much. It is working perfectly now! I voted you up. I was notified that it counted but won't display publicly since I'm new to the site. – Vienne Feb 06 '19 at 05:39
  • No problem :) You should mark answers that are correct instead of voting up. That way if another user comes to this thread they know what answer fixed the issue. – Second2None Feb 06 '19 at 05:40
  • I just realized that when I click "return" on the 2nd page and it sends me back to the first page ... my error messages are being displayed now to the right of the input boxes .. They should only appear if the data isn't valid but they are appearing now before any data is entered. Do you know how I could correct this? Thank you! – Vienne Feb 06 '19 at 05:42
  • I just marked this answer as correct. I'm still learning how this site works. Thank you for explaining – Vienne Feb 06 '19 at 05:43
  • I've updated my code to show the changes and the new problem that I'm having – Vienne Feb 06 '19 at 05:48
  • I'll update my answer, 1 second. You need to check if $_POST is set before you run filters on them – Second2None Feb 06 '19 at 05:49
  • Underneath the edit line I've run over your code and have tested it. It works fine :) try it – Second2None Feb 06 '19 at 06:05
  • I've obviously made a mistake somewhere. The confirm is sending me to the second page again even when the inputs are empty. Going to go over it again now and try to figure out what I've messed up. Thank you for your time! – Vienne Feb 06 '19 at 06:10
  • I copied and pasted all of your code into my file and ran it ..and the confirm button sends me to the 2nd page without data being entered. Not sure how it's working for you and not for me. – Vienne Feb 06 '19 at 06:15
  • Sorry made a mistake with the if statement, needed to return validation false on those variables. Works as desired now. – Second2None Feb 06 '19 at 06:42
  • Doesn't work for me. Confirm button no longer directs to second page even when data is entered and correct and I'm getting errors including: Undefined index: confirmSubmit (line 54) ... and "string(7) "Confirm" bool(false) bool(false)". I'm working to figure things out .. May have to post new question with updated code. It seems I can fix one problem but fixing it creates additional ones. I appreciate your help, though. – Vienne Feb 06 '19 at 07:06
0

Perhaps something like this:

IF ( got a submission ) {
   do validations
   IF (!valid) {
      show errors or message
   } 
   ELSE  { // its all ok
     show confirmation html (could be included file)
   }
}
ELSE { // no submission  - first time here
   show initial html 
}

Another way to look at it is: Right now your form submission goes to confirm.php. One could do the validation in index.php and if valid then redirect to confirm.php BUT then one needs to not have people ending up at confirm.php with coming from the form submission.

If you leave the validation in the confirm.php, then you'd have to redirect back to index.php if it fails validation. One can redirect using http://php.net/manual/en/function.header.php. THis may also help: PHP- Redirect to another page.

Personally I prefer keeping it in one file.

anmari
  • 3,830
  • 1
  • 15
  • 15
0

Use this and try to submit your form. Let me know if you still face the issue.

if($_POST && $_POST['sales_price']!='' && $_POST['discount_amount']!=''){

//To next page

var_dump($_POST);exit;

} else {

//back to index page

//header('Location: http://www.example.com/');

}

Mobeen Ahmed
  • 121
  • 7
  • Thank you for responding but this is not working. The else statement is be rejected. "statement has empty body". Should I be typing the code in a different way? – Vienne Feb 06 '19 at 05:21
  • you have to use if and else condition in this way, adjusting you own code. in else condition please use header('Location: your main page path here'); – Mobeen Ahmed Feb 06 '19 at 05:27