validation not working correctly

I think things just need to be re-ordered and better organized. i’ll take a better look at it tonight when i get home from work.

I finally got some free time and reviewed your code. Thanks for posting it all…

You are almost there! Yea!

The problem is in the reposting of the page. You can not create a function and have HTML code inside it.
You have to “ECHO” or “PRINT” the html code. Remember that a PHP FUNCTION is code not HTML.
Sooo, it the redisplayform function code, do not use this:
–> ?>

Calculate Your Pay

<–
But, instead do it this way:
–> echo “

Calculate Your Pay

”; <–

You will have to alter the rest of the function to echo out html instead of dropping back to html.
Hope that makes sense. Your project is nearly there. Good luck…

Many, many thanks for any help you can give me.

A couple more items to review…
Normally the flow would be this way:

  1. User input on the original html form. (This works now, all done!)

  2. PHP page gets the data entered by the user (This works now, all done!)

  3. User data is validated for errors and if any these are posted back. (This is partly in place now.)

  4. Calculations are made from user data and results posted back. (Works somewhat now.)

So, 1,2,4 are working. So, it is just the validation you need to tune up. Here are some comments on this project to help you learn how to fix it. (I can give you the correct code if you don’t want to learn.)

First, your calculations are incorrect for overtime. hours-worked times rate + hours-worked-40 time 1.5 gives you too much money! if you already add hours*rate that is already 40 hours. So the hours-worked-40 should be times one half the rate. The old line is:
–> $payCheck = ($hoursWorked * $wages) + (($hoursWorked - 40) * $wages * 1.5); <–
New version:
–> $payCheck = ($hoursWorked * $wages) + (($hoursWorked - 40) * $wages * .5); <–

Also, since this is a small project, I would not even use functions, but, it is very nice to understand how to use them, so it is up to you. If needed for the course, then use them. If you are using them, they should all be your first PHP code. Functions are much easier to use if they are done and out of the way. The actual code for the real process would be only a few calls to the functions. Something, in general, like this:
$errorcode=0;
$hoursWorked = validateInput ($_POST[‘Hours’]);
//NOTE the above validateinput would make sure an entry was made in the variable
// and if not, it would set $errorcode=1 and $errormessage=“no hours worked entered”
$wages = vali… etc…
if ($errorcode==1) {
// errors were found
echo "can not complete your form, Error: " . $errormessage . “!”;
} else {
// no errors found…
redisplayform();
}
***** This is just a sample of the flow of your current project plan. If you fix all of these, repost the new code. If you want a solution, let us know… ****

Oh, also. Usually, I only use functions for routines that are repeated several times. Like formatted strings or dates. What is nice about functions is that you can keep all of the ones you use in another file called “functions.php” and just include it in your current file and all the functions are now available. Good luck.

I appreciate all the tips! I really would like to have a solution. I’m working on new assignments about permissions, directory & file structure and writing data to files. I’d really appreciate the help to getting the code like I explained in my previous post. If you could help me with it, that would be fantastic.

ok, this code works, its been tested.
[php]

<?php if(isset($_POST['Submit'])) { $hoursWorked = $_POST['Hours']; $wages = $_POST['Wage']; $errorCount = ""; if(is_numeric($hoursWorked) && is_numeric($wages)) { if($hoursWorked >= 40) { $payCheck = ($hoursWorked * $wages) + (($hoursWorked - 40) * $wages * 1.5); } else { $payCheck = $hoursWorked * $wages; } $final = " Your Wages Earned:

You worked $hoursWorked hours at a rate of $".$wages." an hour.

Your pay total is: $".$payCheck." minus federal and state withholding.

"; } else { $errorCount = "This must be numerical"; } } ?> Pay Calculation

Calculate Your Pay

Number of Hours Worked:

Hourly Wage:

<?=$final?>
echo $errorCount; [/php]

You can add in whatever validation i didn’t put in, but it works :slight_smile: Its all on 1 page now and its been organized. I took out the functions since they weren’t needed. Basic formatting, feel free to change it to whatever you want.

Hope it helps :slight_smile:

Okay, have to run out for a little bit, will do it when I get back…

WITH or WITHOUT functions???

I did it without the functions simply because they aren’t needed and all he’s validating is if the input is a number or not. i just forgot to put the echo in there for the error message.

Thanks Richei, I am sure that will help him…

Here is my version with functions, since I thought he may want to learn how they are used.
(Basically his code altered to work correctly…)
Just the PHP page, the original page was okay as-is. I reformatted it to be easier to read…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pay Calculations</title>
</head>
<body>
<?php
function displayRequired($fieldName) {
         echo "The field \"$fieldName\" is required to calculate the wages earned.<br />\n";
         }
function validateInput($data, $fieldName) {
         global $errorCount;
		 //if the field is empty, it calls the display required function, adds to errorCount and returns the value of empty or null;
		 //otherwise it shows the data entered in the field
         if (empty($data)) {  
            displayRequired($fieldName);
            $errorCount++;
            $retval = "";
         }else{
            return ($data);
            }
         }
function redisplayForm($hoursWorked, $wages) {
         echo "<h1>Calculate Your Pay</h1>";
         echo "<form name=\"paycheck\" action=\"process_Paycheck.php\" method=\"post\">";
         echo "<p>Number of Hours Worked: <input type=\"text\" name=\"Hours\" value=" . $hoursWorked . " /><br />";
         echo "Hourly Wage: <input type=\"text\" name=\"Wage\" value=" . $wages . "/><br />";
         echo "<input type=\"reset\" value=\"Clear Form\" />&nbsp;&nbsp;<input type=\"submit\" name=\"Submit\" value=\"Send Form\" />";
         echo "</form>";
         }
         
$errorCount=0;
$hoursWorked = validateInput ($_POST['Hours'], "Hours");
$wages = validateInput($_POST['Wage'], "Wage");

if (is_numeric($hoursWorked) && is_numeric($wages)){
    if ($hoursWorked <= 40) {
       $payCheck = ($hoursWorked * $wages);
       echo "<h1>Your Wages Earned</h1><p>You worked <strong>" . $hoursWorked . "</strong> hours at a rate of <strong>$" . $wages . "</strong> an hour.</p>";
	   echo "<h3>Your pay total is:  <strong>$" . $payCheck . "</strong></h3><br /><p><a href='Paycheck.html'>Try Again?</a></p>";
     }else{
       $payCheck = ($hoursWorked * $wages) + (($hoursWorked - 40) * $wages * .5);
       echo "<h1>Your Wages Earned</h1><p>You worked <strong>" . $hoursWorked . "</strong> hours at a rate of <strong>$" . $wages . "</strong> an hour.</p>";
	   echo "<h3>Your pay total is:  <strong>$" . $payCheck . "</strong></h3><br /><p><a href='Paycheck.html'>Try Again?</a></p>";
    }
 }else{
    echo  "<p>Only numbers can be used.  Press the Back button and Please try again.</p>";
}

if ($errorCount>0) {
    echo "Please enter the information.<br />\n";
    redisplayForm($hoursWorked, $wages);
}

?>
</body>
</html>

Either way, the code works :slight_smile:

Just a note:
++var vs var++
when as a statement alone, there is no difference
the difference between the two is when used in expressions

$count =0;
if(++$count) echo 'Got sumfing'.PHP_EOL;
$count=0;
if($count++) echo 'Got sum more'.PHP_EOL;

Simple demonstration, the first comparison will be true, and thus echo
the second, will be false.

it’s just a matter of when you want the increment to occur, before the expression is evaluated or after to keep it simple.

anyway a lot of fix ups, redone the first part, to do proper sanitize & validate.

and no longer need html page and a php script, since the html page is already within the php script.

so a few adjustments here and there

[code]

Pay Calculations <?php

function ValidateInput($name,$field,$validator,$required=FALSE)
{
global $errors;
if(empty($field) && !$required)
return NULL;
if(!empty($validator) && (($validfield=call_user_func($validator,$field))===FALSE))
{
$errors[$name]=TRUE;
return $field;
}
return $validfield;
}

function ValidateHours($hours)
{
if(is_numeric($hours) && ($hours=floatval($hours))>0 && floatval($hours/0.25)==intval($hours/0.25))
return $hours;
else
return FALSE;
}

function ValidateWage($wage)
{
if(is_numeric($wage) && $wage>0 && intval($wage100)==$wage100)
return floatval($wage);
else
return FALSE;
}
function displayRequired($fieldName)
{
echo “The field “$fieldName” is required to calculate the wages earned.
\n”;
}
$errors=array();
if(isset($_POST[‘Submit’]))
{
$hoursWorked = validateInput (‘Hours’,$_POST[‘Hours’],‘ValidateHours’,TRUE);
$wages = validateInput (‘Wage’,$_POST[‘Wage’],‘ValidateWage’,TRUE);
} else {
$hoursWorked = $Wages = 0;
}

function DisplayForm($hoursWorked, $wages) {
global $errors;
?>

Calculate Your Pay

<?php if(isset($errors['Hours'])) displayRequired('Hours'); ?>

Number of Hours Worked:
<?php if(isset($errors['Wage'])) displayRequired('Wage'); ?> Hourly Wage:

  

<?php } //should I have created a function for this? If so, How would I call it? if (count($errors)) { echo "Please enter the information.
\n"; DisplayForm($hoursWorked, $wages); } elseif(isset($_POST['Submit'])) { if ($hoursWorked <= 40) { $payCheck = ($hoursWorked * $wages); echo "

Your Wages Earned

You worked $hoursWorked hours at a rate of $$wages an hour.

Your pay total is: $$payCheck


Try Again?

"; } else { $payCheck = ($hoursWorked * $wages) + (($hoursWorked - 40) * $wages * 1.5); echo "

Your Wages Earned

You worked $hoursWorked hours at a rate of $$wages an hour.

Your pay total is: $$payCheck


Try Again?

"; } } else { DisplayForm(NULL,NULL); } ?> [/code]

Now I hope you can follow the code and actually understand whats going on :slight_smile:

Yes, but…
echo $x++;
and
echo ++$x;

Are NOT the same! In formula’s, for loops and whatever, it is best to use $x+1, in my opinion so there is no thinking involved. But, Laffin, you are 100% correct.

I did say when used as a statement alone, your example demonstrates an expression

$x=0;
// No difference since the value is never used
$x++;
if($x==1) foo();
++$x;
if($x==2) bar();

++ operator as a statement example.

I definately use them operators, but I’m prolly more advanced than most coders since I do have roots in C :slight_smile:
so expressions, boolean math, etc within a statement is a norm, so ++ operator comes in handy :slight_smile:

Sponsor our Newsletter | Privacy Policy | Terms of Service