jharvie Posted January 14, 2013 Share Posted January 14, 2013 Hello there, I have a script that I have created. The purpose of the script is a grade entry form. What it does, is the user enters the first and last name, course number, and the grade. The grade is converted from a number grade to a letter, such as A or A+ and redisplayed back to the user, as well as appended to a text file. The problem I am having is that I need to make sure that a valid number (between 0 and 100) is entered into the grade form, and make sure that it doesnt contain any letters, or just letters at all. Currently I have it so that if it contains a number, such as 50, it will convert it to the letter grade as required. If I enter 101, it will redisplay the page and make the user enter a correct grade. If a number such as 60 is entered with a letter, it will also make the user re-enter the information. However, if just letters are entered, it processes the form and displays the output as the same letters that were entered (when it should redisplay the page and ask the user to enter the correct information). Also, it will not display the output as (A+) or (A-) for the grades in those categories. Instead I had to put it to display (Aplus) or (Aminus), as it would not seem to print symbols in the output. If there are any suggestions as to what I have been doing wrong, that would be great. The way the program works is the user enters the information initially into an html version of the page that has to send the information to this php version. If the user enters anything incorrectly, then the php page just echo's back a copy of the original page, but displays a message notifying the user that there was an error. The code is attached below. Thanks in advance! process_EnterGrades.php Quote Link to comment Share on other sites More sharing options...
premiso Posted January 14, 2013 Share Posted January 14, 2013 (edited) Please post the relevant code inline instead of attaching. Since I do not know where the relevant part is / cba to look here is the code: <HTML> <?php // This defines the name of the file to be saved with the user information and grades $Savedfile = "FinalGrades.txt"; // This opens the text document named FinalGrades.txt and adds the new data. If it cannot open it, it then displays an error message to the user. $file = fopen($Savedfile,'a') or die("Cannot open file, check permissions"); //This clears the form fields if it is reset $clear = $_POST['reset']; if ($clear == "reset") { } else { //Defines the form variables $firstname = $_POST['firstname']; $lastname = $_POST['lastname']; $coursenumber = $_POST['coursenumber']; $finalgrade = $_POST['finalgrade']; // Uses an if statement to determine the grade as long as the fields are not empty } if (!empty($firstname) and !empty($lastname) and !empty($coursenumber) and !empty($finalgrade) and ($finalgrade >-1 and $finalgrade <101) and is_numeric($finalgrade)) { if (($finalgrade >=0) && ($finalgrade <=59) && is_numeric($finalgrade)){ $finalgrade="F"; } if (($finalgrade >=60) && ($finalgrade <=69) && is_numeric($finalgrade)){ $finalgrade="D"; } if (($finalgrade >=70) && ($finalgrade <=79) && is_numeric($finalgrade)) { $finalgrade="C"; } if (($finalgrade >=80) && ($finalgrade <=85) && is_numeric($finalgrade)) { $finalgrade="B"; } if (($finalgrade >=86) && ($finalgrade <=90) && is_numeric($finalgrade)) { $finalgrade="Aminus"; } if (($finalgrade >=91) && ($finalgrade <=95) && is_numeric($finalgrade)) { $finalgrade="A"; } if (($finalgrade >=96) && ($finalgrade <=100) && is_numeric($finalgrade)){ $finalgrade="Aplus"; } } // If a field is left empty it echos back the main page with extra information that advises the user to fill in information for all fields. if (empty($firstname) or empty($lastname) or empty($coursenumber) or empty($finalgrade) or (!ctype_alpha($finalgrade))){ echo " <html> <!-- This Allows the use of css files for the background and font format --> <STYLE TYPE='text/css' title='styleid' media='all'></STYLE> <head> <!-- This Sets the title of the page --> <title> Enter Course Grades </title> <!-- This imports the css file created to use as the background- defines the styles such as bg image and colors --> <link rel='stylesheet' type='text/css' href='background.css' /> </head> <body> <!-- Centers the company logo image as well as sets the size of 450x150 --> <center><img src='Logo.jpg' alt='Company Logo' width='450' height=150'></center> <!-- Creates the first heading for the page --> <center><h1> Enter Course Grades </h1></center> <center><h2> Please fill out all fields </h2></center> <br> <!-- Creates the form for the grade entries, and when the submit button is pressed, the form created will execute the php file process_EnterGrades.php , which will process the grades appropriately. --> <center> <Form action ='process_EnterGrades.php' METHOD = 'post'> <!-- Specifies the input types for the form created --> First Name: <input type='text' name='firstname' size='20'> Last Name: <input type='text' name='lastname' size='20'> <br> <br> <br> Course Number: <input type='text' name='coursenumber' size='20'> Final grade in percent (%): <input type='text' name='finalgrade' size='20'> </center> <br> <!-- This creates the submit buttons --> <center> <table border='3' bordercolor='red'> <tr> <td> <input type='submit' value='Submit Your Entries'> <td> </FORM> <!-- Below creates a second form that is used to clear the entries --> <FORM NAME = 'gradesclear' ACTION = 'gradesclear.php' METHOD = 'post'> <td> <input type='submit' value='Clear Your Entries'> </td> </tr> </center> </FORM> </body> </html> "; } // Displays results entered in the form in a table that is easily interpreted by the user else { echo "<link rel='stylesheet' type='text/css' href='background.css' />"; echo "<center><img src='Logo.jpg' alt='Company Logo' width='450' height='150'></center>"; echo "<br>"; echo "<br>"; echo "<br>"; echo "<br>"; echo "<center><TABLE BORDER='1' WIDTH='50%'> <TR> <TD WIDTH='50%'> First Name: $firstname </TD> <TD WIDTH='50%'>Last Name: $lastname </TD></TR> </TABLE></center>"; echo "<center><TABLE BORDER='1' WIDTH='50%'> <TR> <TD WIDTH='50%'> Course Number: $coursenumber </TD> <TD WIDTH='50%'>Final Grade: $finalgrade </TD></TR> </TABLE></center>"; //Below will define the format which the fields will be saved to the text document specified at the beginning of this document. $StringData = "First Name: $firstname Last Name: $lastname Course Number: $coursenumber Final Grade: $finalgrade \n "; fwrite($file, $StringData); fclose($file); } ?> </HTML> Edited January 14, 2013 by premiso Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 14, 2013 Share Posted January 14, 2013 (edited) You can just use is_numeric() validation, other way is to create white list with select and all available grades as options (however second one needs validation too as somebody could change option values). You can also pass only numbers like that: $grade = preg_replace("/[^0-9]/","", $grade); One thing: if something is wrong with input data and form is displayed once again for correction, it's cool to import values to inputs and tag input that must be corrected with red border, etc. Edited January 14, 2013 by BagoZonde Quote Link to comment Share on other sites More sharing options...
cpd Posted January 14, 2013 Share Posted January 14, 2013 From looking at the code I can see your control flow is a little ski-wiff. Lets work through this systematically: I can't see in your mark-up where you've defined a "reset" button and even if you had there's no need to test for it in PHP as it won't refresh the page. To test if something's submitted use isset($_POST['submitButtonName'] Instead of setting each variable as you've done, use extract($_POST), it'll save a lot of time. You query if the value is_numeric() in ever if statement, why not have a single if statement wrapping all other logic that requires is_numeric. This is far better control flow. Consider using range() to determine if a grade is within a range: if(in_array($finalgrade, range(0, 59))) { Use the HTML Entity code for plus and minus: plus = + and minus = + If the problem persists use the Regex to test if the input is an integer: if(preg_match('/[0-9]{1,3}/', $finalgrade)) { // Code omitted } Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 So what I have attempted to do is to add preg_replace( "/[^0-9_]/", "", $finalgrade ) Which I am assuming will replace any characters other than the numbers 0-9 with blank space. I have then added in preg_match("/[^a-zA-Z_]",$finalgrade) for the echo part which I am under the assumption should tell it that if it detects any letters being entered in the final grade box then it should echo back the error page. However, the form is still accepting submissions with all letters. If there is a number with the letters, then it displays the error. It also functions correctly if just a correct number grade is entered (with no foreign characters). Another question though is how come for the part if (($finalgrade >=86) && ($finalgrade <=90) && is_numeric($finalgrade)) { $finalgrade="Aminus";} I have to have it display (Aminus) instead of simply displaying (A-). If I tell it to display (A-), then it just detects any numbers >=86 and <=90 as invalid as if it contains a letter. Sorry for my lack of php experience, as well as sorry if this is not explained the best. My current code is below: <HTML><?php // This defines the name of the file to be saved with the user information and grades$Savedfile = "FinalGrades.txt"; // This opens the text document named FinalGrades.txt and adds the new data. If it cannot open it, it then displays an error message to the user.$file = fopen($Savedfile,'a') or die("Cannot open file, check permissions"); //This clears the form fields if it is reset$clear = $_POST['reset']; if ($clear == "reset") {} else { //Defines the form variables$firstname = $_POST['firstname'];$lastname = $_POST['lastname'];$coursenumber = $_POST['coursenumber'];$finalgrade = $_POST['finalgrade']; // Uses an if statement to determine the grade as long as the fields are not empty}if (!empty($firstname) and !empty($lastname) and !empty($coursenumber) and !empty($finalgrade) and ($finalgrade >-1 and $finalgrade <101) and is_numeric($finalgrade) and preg_replace( "/[^0-9_]/", "", $finalgrade )) { if (($finalgrade >=0) && ($finalgrade <=59) && is_numeric($finalgrade)){ $finalgrade="F";} if (($finalgrade >=60) && ($finalgrade <=69) && is_numeric($finalgrade)){ $finalgrade="D";} if (($finalgrade >=70) && ($finalgrade <=79) && is_numeric($finalgrade)) { $finalgrade="C";} if (($finalgrade >=80) && ($finalgrade <=85) && is_numeric($finalgrade)) { $finalgrade="B";} if (($finalgrade >=86) && ($finalgrade <=90) && is_numeric($finalgrade)) { $finalgrade="Aminus";} if (($finalgrade >=91) && ($finalgrade <=95) && is_numeric($finalgrade)) { $finalgrade="A";} if (($finalgrade >=96) && ($finalgrade <=100) && is_numeric($finalgrade)){ $finalgrade="Aplus"; } } // If a field is left empty it echos back the main page with extra information that advises the user to fill in information for all fields.if (empty($firstname) or empty($lastname) or empty($coursenumber) or empty($finalgrade) or (!ctype_alpha($finalgrade)) or preg_match("/[^a-zA-Z_]",$finalgrade)){ echo " <html><!-- This Allows the use of css files for the background and font format --><STYLE TYPE='text/css' title='styleid' media='all'></STYLE> <head> <!-- This Sets the title of the page --><title> Enter Course Grades </title> <!-- This imports the css file created to use as the background- defines the styles such as bg image and colors --><link rel='stylesheet' type='text/css' href='background.css' /></head> <body> <!-- Centers the company logo image as well as sets the size of 450x150 --><center><img src='Logo.jpg' alt='Company Logo' width='450' height=150'></center> <!-- Creates the first heading for the page --> <center><h1> Enter Course Grades </h1></center><center><h2> Please fill out all fields </h2></center><br> <!-- Creates the form for the grade entries, and when the submit button is pressed, the form created will execute the php file process_EnterGrades.php , which will process the grades appropriately. --><center><Form action ='process_EnterGrades.php' METHOD = 'post'> <!-- Specifies the input types for the form created --> First Name: <input type='text' name='firstname' size='20'>Last Name: <input type='text' name='lastname' size='20'><br><br><br>Course Number: <input type='text' name='coursenumber' size='20'>Final grade in percent (%): <input type='text' name='finalgrade' size='20'></center><br><!-- This creates the submit buttons --><center><table border='3' bordercolor='red'><tr><td><input type='submit' value='Submit Your Entries'><td></FORM> <!-- Below creates a second form that is used to clear the entries --><FORM NAME = 'gradesclear' ACTION = 'gradesclear.php' METHOD = 'post'><td><input type='submit' value='Clear Your Entries'></td></tr></center></FORM> </body> </html> ";} // Displays results entered in the form in a table that is easily interpreted by the userelse {echo "<link rel='stylesheet' type='text/css' href='background.css' />";echo "<center><img src='Logo.jpg' alt='Company Logo' width='450' height='150'></center>";echo "<br>";echo "<br>";echo "<br>";echo "<br>";echo "<center><TABLE BORDER='1' WIDTH='50%'> <TR> <TD WIDTH='50%'> First Name: $firstname </TD> <TD WIDTH='50%'>Last Name: $lastname </TD></TR> </TABLE></center>";echo "<center><TABLE BORDER='1' WIDTH='50%'> <TR> <TD WIDTH='50%'> Course Number: $coursenumber </TD> <TD WIDTH='50%'>Final Grade: $finalgrade </TD></TR> </TABLE></center>";//Below will define the format which the fields will be saved to the text document specified at the beginning of this document.$StringData = "First Name: $firstname Last Name: $lastname Course Number: $coursenumber Final Grade: $finalgrade \n ";fwrite($file, $StringData);fclose($file);}?></HTML> Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 I have also tried if (($finalgrade >=96) && ($finalgrade <=100) && is_numeric($finalgrade)){ $finalgrade="A"and"+"; in order to print the plus sign, but when I run this, it will only print out a result of "A" instead of "A+". Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 14, 2013 Share Posted January 14, 2013 I'm not sure what you want to do, but... Your code will display graduation only if form was accepted (no errors occured). That way you're sure that $finalgrade is numeric coz your code parse all values. If there's something wrong, just set $validate flag to false. Just do it that way: $validate=true; //Here your code will pass form entry, if something is wrong just set $validate=false; ... //Here your code will transform numeric grade to letter grade if ($validate){ //If no errors after submit if ($finalgrade>=0 && $finalgrade<=59){ $finalgrade='F'; }else if($finalgrade>=60 && $finalgrade<=69){ $finalgrade='D'; }else if(...and so on...){ }else if($finalgrade>=96 && $finalgrade <=100){ $finalgrade="A+"; } //Display grade as letter print $finalgrade; }else{ //Display form once again for correction } Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 What I want the code to do is allow the user to enter the first and last name, course, and the final grade in a percentage (between 0 and 100). I want it so that if they enter a correct number, it will convert it to a letter grade, display it back to the user as well as append it to a text file. I want the script so that if the user enters a number over 100, itll echo back the original form with a message stating that there was an error. It also has to be configured in such a way that if the user enters a number grade but has any letters, it will echo back the error page. Also, if the user only enters letters instead of a valid number, it again echos back the page. Currently it wont process an output stating (A+), as it doesnt seem to like the "+" symbol, but it will process the output if written as (Aplus). This is something I have been unable to figure out. Also, currently if the user enters a grade between 0 and 100, it will correctly convert it to a letter grade. If the user enters a number along with a letter, it will display the error, as it should. However, if the user only enters letters, the form proceses and instead of displaying a converted grade, it will display what they entered and append that to the text file, when it should display an error and not allow letters to be entered. Again, I apologize for my lack of knowledge with php, as I am trying to explain what this needs to do as best as possible. Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 14, 2013 Share Posted January 14, 2013 (edited) Here you go with whole process_EnterGrades.php script. No script for clearing needed. <html> <head> <title> Enter Course Grades </title> <link rel='stylesheet' type='text/css' href='background.css' /> </head> <body> <center><img src='Logo.jpg' alt='Company Logo' width='450' height=150'></center> <br> <center> <?php // This defines the name of the file to be saved with the user information and grades $Savedfile = "FinalGrades.txt"; $field=array(); if ($_POST){ //if form submitted $defined_error=' style="border: 2px solid #aa2200;"'; if ($_POST['clear']){ //This clears the form fields if it is reset and... that's all! }else{ //Defines the form variables $form=array('firstname', 'lastname', 'coursenumber', 'finalgrade'); $error=''; foreach($form as $input){ $field[$input]=$_POST[$input]; if (!$field[$input]){ $error[$input]=1; } } if (!is_numeric($field['finalgrade'])){ $error['finalgrade']=1; }else if ($field['finalgrade']<0 || $field['finalgrade']>100){ $error['finalgrade']=1; }else{ $range=array( 'F'=>array(0, 59), 'D'=>array(60, 69), 'C'=>array(70, 79), 'B'=>array(80, 85), 'A-'=>array(86, 90), 'A'=>array(91, 95), 'A+'=>array(96, 100), ); foreach($range as $finalgrade_letter=>$finalgrade_range){ //print 'range from ' . $finalgrade_range[0] . ' to ' . $finalgrade_range[1] . '<br />'; //uncomment this line if you're confused $range_array=range($finalgrade_range[0], $finalgrade_range[1]); if (in_array($field['finalgrade'], $range_array)){ break; //letter found, so let's get out of here } } echo "<br>"; echo "<br>"; echo "<br>"; echo "<br>"; //Data for displaying $StringData = '<tr><td>First Name: ' . $field['firstname'] . '</td>'; $StringData.= '<td>Last Name: ' . $field['lastname'] . '</td></tr>'; $StringData.= '<tr><td>Course Number: ' . $field['coursenumber'] . '</td>'; $StringData.= '<td>Final Grade: ' . $finalgrade_letter . '</td></tr>'; print '<center>'; print '<table border=1 width="50%">'; print $StringData; print '</table>'; print '</center>'; //Data for document //Below will define the format which the fields will be saved to the text document specified at the beginning of this document. $StringData = 'First Name: ' . $field['firstname']; $StringData.= ' Last Name: ' . $field['lastname']; $StringData.= ' Course Number: ' . $field['coursenumber']; $StringData.= ' Final Grade: ' . $finalgrade_letter . '\n'; //This opens the text document named FinalGrades.txt and adds the new data. If it cannot open it, it then displays an error message to the user. $file = fopen($Savedfile,'a') or die("Cannot open file, check permissions"); fwrite($file, $StringData); fclose($file); } } } if ($error || !$_POST || $_POST['clear']){ ?> <h1> Enter Course Grades </h1> <h2> Please fill out all fields </h2> <Form action ='process_EnterGrades.php' method="POST"> <?php $error_class=$error['firstname']?$defined_error:''; print 'First Name: <input type="text" name="firstname" size="20" value="' . $field['firstname'] . '"' . $error_class . '>'; $error_class=$error['lastname']?$defined_error:''; print 'Last Name: <input type="text" name="lastname" size="20" value="' . $field['lastname']. '"'.$error_class.'>'; ?> <br> <br> <br> <?php $error_class=$error['coursenumber']?$defined_error:''; print 'Course Number: <input type="text" name="coursenumber" size="20" value="' . $field['coursenumber'] . '"'.$error_class.'>'; $error_class=$error['finalgrade']?$defined_error:''; print 'Final grade in percent (%): <input type="text" name="finalgrade" size="20" value="' . $field['finalgrade'] . '"' . $error_class . '>'; ?> </center> <br> <!-- This creates the submit buttons --> <center> <table border="3" bordercolor="red"> <tr> <td> <input type="submit" value="Submit Your Entries"> </td> </tr> </table> </form> <!-- Below creates a second form that is used to clear the entries --> <form name="gradesclear" action="process_EnterGrades.php" method="POST"> <td> <input type="submit" value="Clear Your Entries"> <input type="hidden" name="clear" value="1"> </td> </tr> </FORM> <?php } ?> </center> </body> </html> Edited January 14, 2013 by BagoZonde Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 (edited) Here you go with whole process_EnterGrades.php script. No script for clearing needed. <html> <head> <title> Enter Course Grades </title> <link rel='stylesheet' type='text/css' href='background.css' /> </head> <body> <center><img src='Logo.jpg' alt='Company Logo' width='450' height=150'></center> <br> <center> <?php // This defines the name of the file to be saved with the user information and grades $Savedfile = "FinalGrades.txt"; $field=array(); if ($_POST){ //if form submitted $defined_error=' style="border: 2px solid #aa2200;"'; if ($_POST['clear']){ //This clears the form fields if it is reset and... that's all! }else{ //Defines the form variables $form=array('firstname', 'lastname', 'coursenumber', 'finalgrade'); $error=''; foreach($form as $input){ $field[$input]=$_POST[$input]; if (!$field[$input]){ $error[$input]=1; } } if (!is_numeric($field['finalgrade'])){ $error['finalgrade']=1; }else if ($field['finalgrade']<0 || $field['finalgrade']>100){ $error['finalgrade']=1; }else{ $range=array( 'F'=>array(0, 59), 'D'=>array(60, 69), 'C'=>array(70, 79), 'B'=>array(80, 85), 'A-'=>array(86, 90), 'A'=>array(91, 95), 'A+'=>array(96, 100), ); foreach($range as $finalgrade_letter=>$finalgrade_range){ //print 'range from ' . $finalgrade_range[0] . ' to ' . $finalgrade_range[1] . '<br />'; //uncomment this line if you're confused $range_array=range($finalgrade_range[0], $finalgrade_range[1]); if (in_array($field['finalgrade'], $range_array)){ break; //letter found, so let's get out of here } } echo "<br>"; echo "<br>"; echo "<br>"; echo "<br>"; //Data for displaying $StringData = '<tr><td>First Name: ' . $field['firstname'] . '</td>'; $StringData.= '<td>Last Name: ' . $field['lastname'] . '</td></tr>'; $StringData.= '<tr><td>Course Number: ' . $field['coursenumber'] . '</td>'; $StringData.= '<td>Final Grade: ' . $finalgrade_letter . '</td></tr>'; print '<center>'; print '<table border=1 width="50%">'; print $StringData; print '</table>'; print '</center>'; //Data for document //Below will define the format which the fields will be saved to the text document specified at the beginning of this document. $StringData = 'First Name: ' . $field['firstname']; $StringData.= ' Last Name: ' . $field['lastname']; $StringData.= ' Course Number: ' . $field['coursenumber']; $StringData.= ' Final Grade: ' . $finalgrade_letter . '\n'; //This opens the text document named FinalGrades.txt and adds the new data. If it cannot open it, it then displays an error message to the user. $file = fopen($Savedfile,'a') or die("Cannot open file, check permissions"); fwrite($file, $StringData); fclose($file); } } } if ($error || !$_POST || $_POST['clear']){ ?> <h1> Enter Course Grades </h1> <h2> Please fill out all fields </h2> <Form action ='process_EnterGrades.php' method="POST"> <?php $error_class=$error['firstname']?$defined_error:''; print 'First Name: <input type="text" name="firstname" size="20" value="' . $field['firstname'] . '"' . $error_class . '>'; $error_class=$error['lastname']?$defined_error:''; print 'Last Name: <input type="text" name="lastname" size="20" value="' . $field['lastname']. '"'.$error_class.'>'; ?> <br> <br> <br> <?php $error_class=$error['coursenumber']?$defined_error:''; print 'Course Number: <input type="text" name="coursenumber" size="20" value="' . $field['coursenumber'] . '"'.$error_class.'>'; $error_class=$error['finalgrade']?$defined_error:''; print 'Final grade in percent (%): <input type="text" name="finalgrade" size="20" value="' . $field['finalgrade'] . '"' . $error_class . '>'; ?> </center> <br> <!-- This creates the submit buttons --> <center> <table border="3" bordercolor="red"> <tr> <td> <input type="submit" value="Submit Your Entries"> </td> </tr> </table> </form> <!-- Below creates a second form that is used to clear the entries --> <form name="gradesclear" action="process_EnterGrades.php" method="POST"> <td> <input type="submit" value="Clear Your Entries"> <input type="hidden" name="clear" value="1"> </td> </tr> </FORM> <?php } ?> </center> </body> </html> So this solves most of my issue. Now the only thing I am trying to figure out is how to make sure that there is an entry in the First Name, Last Name and Course number boxes, and if not, then I have to have it display the error message. I'm sure this is probably quite simple to do, although I cant seem to figure out what needs to be added in. If I enter just the last name, course number and lets say 89 as a grade, it also displays the table of results with an empty first name, but as well as displays the error page below the table, saying Please fill out all fields. However, it appends the incomplete submission to the text file. Edited January 14, 2013 by jharvie Quote Link to comment Share on other sites More sharing options...
cpd Posted January 14, 2013 Share Posted January 14, 2013 I can spot a load of things that are unnecessary or can be done a whole lot better in that, sorry BagoZonde. For a start the if($_POST) { doesn't test if the form was submitted. The $_POST superglobal is generated by PHP regardless of whether POST data was submitted or not so this isn't a true test for a form submission. If you both bother looking and synthesising my previous post you'll see pointers on how to improve your code. If you don't bother synthesising it you are wasting my, and anybody else who posts, time. If you don't understand something, bloody well ask. Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 I can spot a load of things that are unnecessary or can be done a whole lot better in that, sorry BagoZonde. For a start the if($_POST) { doesn't test if the form was submitted. The $_POST superglobal is generated by PHP regardless of whether POST data was submitted or not so this isn't a true test for a form submission. If you both bother looking and synthesising my previous post you'll see pointers on how to improve your code. If you don't bother synthesising it you are wasting my, and anybody else who posts, time. If you don't understand something, bloody well ask. I have tried to implement the various suggestions you have given, however nothing has seemed to work correctly. I really appreciate your effort, I just need more assistance with getting this to work correctly!! Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 14, 2013 Share Posted January 14, 2013 (edited) So this solves most of my issue. Now the only thing I am trying to figure out is how to make sure that there is an entry in the First Name, Last Name and Course number boxes, and if not, then I have to have it display the error message. I'm sure this is probably quite simple to do, although I cant seem to figure out what needs to be added in. If I enter just the last name, course number and lets say 89 as a grade, it also displays the table of results with an empty first name, but as well as displays the error page below the table, saying Please fill out all fields. However, it appends the incomplete submission to the text file. Maybe you missed that incorrect fields are styled with red border (you can change it in $defined_error variable) so form is displayed for correction. If you want to add text, just enter under that line or somewhere there: if ($error || !$_POST || $_POST['clear']){ if ($error){ print 'Please fill up fields properly'; } @cpd I don't wrote that stuff from scratch, just edit what I had from jharvie, copy&paste and modified some things. About $_POST that's right, it's just an easy way, but as you see for that simple example - we're passing $form values in foreach loop so only few variables can really go through this code. That's a quick solution which is okay in my opinion, however sorry if you're thinking I'm ignoring your tips. If you want to, just sit and write your piece of code for form submission. Edited January 14, 2013 by BagoZonde Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 14, 2013 Author Share Posted January 14, 2013 (edited) Maybe you missed that incorrect fields are styled with red border (you can change it in $defined_error variable) so form is displayed for correction. If you want to add text, just enter under that line or somewhere there: if ($error || !$_POST || $_POST['clear']){ if ($error){ print 'Please fill up fields properly'; } I did catch on to that part that if the field is incorrect it displays it with a red border, which is a great idea, however, what I mean is that it will still append the data to the text file even if it is missing something such as the first name. I'm not really sure what needs to be added for it to verify that there is an entry in each of the form fields before it actually appends it to the text file. Again, forgive me for my lack of php knowledge, this is really the first bit of programming in php I have attempted. An example of what is happening right now is if I was to leave the first name blank, enter a name for the last name, give it a course number of lets say 58, and a grade of 89. What happens is it will display a table, with the first name column blank, last name gets displayed, course number is displayed and the final grade prints out as an F. The issues is that it will append this data to the text file, as well as below the table, it displays the error page with the first name box outlined in red, indicating that nothing was entered in the first name field. Edited January 14, 2013 by jharvie Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 14, 2013 Share Posted January 14, 2013 (edited) Sorry jharvie, I didn't tested that code! Please change that line: }else{ $range=array( to }else if (!$error){ $range=array( Sorry for that mistake. BTW. I've used in_array() as cpd suggested, so I hope he will not be mad at all ;]. Edited January 14, 2013 by BagoZonde Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 15, 2013 Author Share Posted January 15, 2013 Sorry jharvie, I didn't tested that code! Please change that line: }else{ $range=array( to }else if (!$error){ $range=array( Sorry for that mistake. BTW. I've used in_array() as cpd suggested, so I hope he will not be mad at all ;]. Thank you so much, I have changed the lines as you have suggested, uploaded the updated copy and tried various entries by leaving a field blank, which it will display the error and outline in red as it should. It will also only accept the specified numbers for the grade, which is perfect! I really appreciate your help with this, it has definitely saved a lot of frustration! Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 15, 2013 Author Share Posted January 15, 2013 So now I have discovered one minor little problem. For some reason, if a grade of "0" is entered, it marks it as invalid, while if you enter it as "0.0", it accepts it. Not really sure what may need to be adjusted. <html><head><!-- This Sets the title of the page --><title> Enter Course Grades </title><!-- This imports the css file created to use as the background- defines the styles such as bg image and colors --><link rel='stylesheet' type='text/css' href='background.css' /></head><body><!-- Centers the company logo image as well as sets the size of 450x150 --><center><img src='Logo.jpg' alt='Company Logo' width='450' height=150'></center><br><center> <?php// This defines the name of the file to be saved with the user information and grades$Savedfile = "FinalGrades.txt"; $field=array(); if ($_POST){ //if form submitted //defines that error messages have a red border $defined_error=' style="border: 5px solid #aa2200;"'; if ($_POST['clear']){ //This clears the form fields if it is reset! }else{ //Defines the form variables $form=array('firstname', 'lastname', 'coursenumber', 'finalgrade'); $error=''; foreach($form as $input){ $field[$input]=$_POST[$input]; if (!$field[$input]){ $error[$input]=1; } } if (!is_numeric($field['finalgrade'])){ $error['finalgrade']=1; }else if ($field['finalgrade']<0 || $field['finalgrade']>100){ $error['finalgrade']=1; }else if (!$error){ $range=array( 'F'=>array(0, 59), 'D'=>array(60, 69), 'C'=>array(70, 79), 'B'=>array(80, 85), 'A-'=>array(86, 90), 'A'=>array(91, 95), 'A+'=>array(96, 100), ); foreach($range as $finalgrade_letter=>$finalgrade_range){ $range_array=range($finalgrade_range[0], $finalgrade_range[1]); if (in_array($field['finalgrade'], $range_array)){ break; //letter found, so let's get out of here. This means the submission is not correct } } echo "<br>"; echo "<br>"; echo "<br>"; echo "<br>"; //Data for displaying results back to the user $StringData = '<tr><td>First Name: ' . $field['firstname'] . '</td>'; $StringData.= '<td>Last Name: ' . $field['lastname'] . '</td></tr>'; $StringData.= '<tr><td>Course Number: ' . $field['coursenumber'] . '</td>'; $StringData.= '<td>Final Grade: ' . $finalgrade_letter . '</td></tr>'; print '<center>'; print '<table border=1 width="50%">'; print $StringData; print '</table>'; print '</center>'; //Data for text document //Below will define the format which the fields will be saved to the text document specified at the beginning of this document. $StringData = 'First Name: ' . $field['firstname']; $StringData.= ' Last Name: ' . $field['lastname']; $StringData.= ' Course Number: ' . $field['coursenumber']; $StringData.= ' Final Grade: ' . $finalgrade_letter . ''; //This opens the text document named FinalGrades.txt and adds the new data. If it cannot open it, it then displays an error message to the user. $file = fopen($Savedfile,'a') or die("Cannot open file, check permissions"); fwrite($file, $StringData ."\n"); fclose($file); } }} /*Below specifies that if there is an error dected, it will redisplay the input page, notify the user by displaying a message, as well as outline the form field containing the error in red. */ if ($error || !$_POST || $_POST['clear']){?> <h1> Enter Course Grades </h1> <h2> Please fill out all fields. The field(s) that contain(s) the error(s) is/are outlined in red! </h2> <Form action ='process_EnterGrades.php' method="POST"><?php $error_class=$error['firstname']?$defined_error:''; print 'First Name: <input type="text" name="firstname" size="20" value="' . $field['firstname'] . '"' . $error_class . '>'; $error_class=$error['lastname']?$defined_error:''; print 'Last Name: <input type="text" name="lastname" size="20" value="' . $field['lastname']. '"'.$error_class.'>';?><br><br><br><?php $error_class=$error['coursenumber']?$defined_error:''; print 'Course Number: <input type="text" name="coursenumber" size="20" value="' . $field['coursenumber'] . '"'.$error_class.'>'; $error_class=$error['finalgrade']?$defined_error:''; print 'Final grade in percent (%): <input type="text" name="finalgrade" size="20" value="' . $field['finalgrade'] . '"' . $error_class . '>';?></center><br><!-- This creates the submit buttons --><center><table border="3" bordercolor="red"> <tr> <td> <input type="submit" value="Submit Your Entries"> </td> </tr></table></form><!-- Below creates a second form that is used to clear the entries --><form name="gradesclear" action="process_EnterGrades.php" method="POST"><td><input type="submit" value="Clear Your Entries"><input type="hidden" name="clear" value="1"></td></tr></FORM> <?php}?> </center></body></html> I apologize if the code doesn't display correctly here, something doesn't seem to be working correctly with the code tags. Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 15, 2013 Share Posted January 15, 2013 Oh well, isset() is needed because of 0 value. Try change that piece of code: if (!$field[$input]){ $error[$input]=1; } to: if (!isset($_POST[$input])){ $error[$input]=1; } Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 15, 2013 Author Share Posted January 15, 2013 Oh well, isset() is needed because of 0 value. Try change that piece of code: if (!$field[$input]){ $error[$input]=1; } to: if (!isset($_POST[$input])){ $error[$input]=1; } Only issue now when that is changed is that it will accept the other fields if they are blank... Programming can be quite the joy thats for sure, lol Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 15, 2013 Share Posted January 15, 2013 Sorry, that quick answers without test are really bad. Try with this: foreach($form as $input){ if ($_POST[$input]!=''){ $field[$input]=$_POST[$input]; }else{ $error[$input]=1; } } instead of that: foreach($form as $input){ $field[$input]=$_POST[$input]; if (!$field[$input]){ $error[$input]=1; } } Quote Link to comment Share on other sites More sharing options...
jharvie Posted January 15, 2013 Author Share Posted January 15, 2013 Thank you, that has fixed the problem! I really appreciate all the help you have been with this. Quote Link to comment Share on other sites More sharing options...
BagoZonde Posted January 15, 2013 Share Posted January 15, 2013 You're welcome, sorry for that annoying repairings! It's holy true that coders shouldn't test their scripts. Quote Link to comment Share on other sites More sharing options...
cpd Posted January 15, 2013 Share Posted January 15, 2013 I just wanted to give you a cleaner and slightly easier, in some respects, to understand method for doing this. Using the following classes I wrote in about 30-45 minutes you can easy get grades without any trouble. If something goes wrong it'll spit an error out at you which you can handle however you want. /** * A wrapper for a single grade. Requires upper and lower limits with which it * will compare a mark and determine if the mark is within the range. */ class Grade { /** * @var string The letter this grade represents */ private $letter = null; /** * @var int The lower limit of the grade */ private $lowerLimit = 0; /** * @var nit The upper limit of the grade */ private $upperLimit = 0; /** * Sets the grade, lower limit and upper limit boundaries. * * @param type $letter The grade letter * @param type $lowerLimit The lower grade limit * @param type $upperLimit The upper grade limit */ public function __construct($letter, $lowerLimit, $upperLimit) { $this->setLetter($letter); $this->setLowerLimit($lowerLimit); $this->setUpperLimit($upperLimit); } /** * Retrieves the grade letter * * @return string The grade letter */ public function getLetter() { return $this->letter; } /** * Determines if a mark is within this grade range. * * @param int|double $mark The mark to test against * @return boolean true if in range, else false. */ public function isInRange(Mark $mark) { if($mark->getValue() >= $this->lowerLimit && $mark->getValue() <= $this->upperLimit) { return true; } return false; } /** * Sets the grade letter * * @param string $letter The grade letter. Can be A+ or B- if you like. * @throws IllegalArgumentException */ private function setLetter($letter) { $this->letter = $letter; } /** * Sets the lower grade limit * * @param int $limit The lower grade limit * @throws IllegalArgumentException */ private function setLowerLimit($limit) { if(!is_numeric($limit)) { throw new InvalidArgumentException("Lower limit must be numeric"); } $this->lowerLimit = (int) $limit; } /** * Sets the upper grade limit * * @param int $limit The upper grade limit * @throws IllegalArgumentException */ private function setUpperLimit($limit) { if(!is_numeric($limit)) { throw new InvalidArgumentException("Upper limit must be numeric"); } $this->upperLimit = (int) $limit; } } /** * Mark represents a single mark received from 0 to 100. This class acts as a wrapper object. */ class Mark { /** * @var double The mark given */ private $mark = 0; /** * Performs validation and sets the mark * * @param int|double $mark The mark received * @throws IllegalArgumentException */ public function __construct($mark) { // Is the mark numeric? if(!is_numeric($mark)) { throw new InvalidArgumentException("Mark must be integer or double"); } // Cast it as a double $mark = (double) $mark; // Is the mark within the range if($mark < 0 || $mark > 100) { throw new InvalidArgumentException("A mark must be between 0 and 100"); } $this->mark = $mark; } /** * Retreives the mark * * @return double The mark */ public function getValue() { return $this->mark; } } /** * Grader will return a grade based on the available grades it is given */ class Grader { /** * * @var array An array of possible grades */ private $grades = array(); public function addGrade(Grade $grade) { $this->grades[] = $grade; return $this; } public function addGrades(array $grades) { // Cycles through the grades and attempts to add them foreach($grades as $grade) { if(!($grade instanceof Grade)) { throw new InvalidArgumentException("Grades must be of type Grade"); } $this->addGrade($grade); } } /** * Finds the approriate grade for the mark. * * The first instance of a satisfactory grade will be returned. This means if * there is an overlap between limits in grades the first grade to of been added * via the addGrades() or addGrade() methods will be returned. * * * @param Mark $mark The mark received * @return Grade|null A Grade object if found with satisfactory parametes. If nothing is found null is returned. */ public function getGrade(Mark $mark) { foreach($this->grades as $grade) { if($grade->isInRange($mark)) { return $grade; } } return null; } } You can then implement the following code to use it. If you don't care for how it functions ignore the above and just review what's below. It has been tested and works quite well as is but there's always improvements to be made. // Has the form been submitted? if(isset($_POST['submissionButtonName'])) { // Create a grader and add marks to it. $grader = new Grader(); $grader->addGrade(new Grade("A+", 96, 100))->addGrade(new Grade("A", 92, 95))->addGrade(new Grade("A-", 88, 91)); try { // Create a mark object using the $_POST data. // The post field name used here should be the same as the one used to enter the mark $mark = new Mark($_POST['mark']); // Was a grade found? If so echo it else echo a message saying we couldnt find a grade based on the available grades. if(($grade = $grader->getGrade($mark)) === null) { echo "Could not find a grade"; } else { echo $grade->getLetter(); } } catch(InvalidArgumentException $e) { // Change how you handle the error... var_dump($e->getMessage()); } } ?> <html> <body> <form method="post"> <input type="text" name="mark" /> <input type="submit" name="submissionButtonName" value="Mark" /> </form> </body> </html> I just thought another view on it would be helpful as I ranted before about how I disliked the code. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.