-2

I have this easy programming exercise and I'm trying to do it in PHP: Determine if a student pass or not the course. The student will pass the course if his average of three grades is greater than or equal to 15. Show a message if the student passes or not and validate the three grades before you calculate the average. Show an error message if any grade if wrong.

I have it in both pseudo-code and pseint, so it is easy to validate because I use a do-while loop and everytime it asks me for typing a number and I do it wrong, it validates the grades:

Algorithm Exercise14
Define grade1, grade2, grade3, prom as Real;
Repeat
    print "Type the first grade: ";
    read grade1;
    if (grade1<0 | grade1>20) 
        print "Error! Invalid grade, type a valid grade.";
    endif
Until (grade1>=0 & grade2<=20);
Repeat
    print "Type the second grade: ";
    read grade2;
    if (grade2<0 | grade2>20) 
        print "Error! Invalid grade, type a valid grade.";
    endif
Until (grade2>=0 & grade2<=20);
Repeat
    print "Type the third grade: ";
    read grade3;
    if (grade3<0 | grade3>20) 
        print "Error! Invalid grade, type a valid grade.";
    endif
Until (grade3>=0 & grade3<=20);
prom = (grade1+grade2+grade3)/3;
if (prom>=15) 
    print "The student passed the course!";
    print "The average is: " prom;
else
    print "The student did not pass the course.";
    print "The average is: " prom;
endif
endAlgorithm

Now, I want to do this but in PHP. My problem is that I cannot validate in this way because if I do it, the browser just takes a lot of time to react and it does nothing, so I have looked on the internet and I need some function to validate but I'm not sure. I'm learning PHP so, excuse me if this is a repeated question or it is to easy but I want to know because I'm learning.

The final question is, how can I validate those fields if I do it with PHP and obviously, HTML5?

PHP code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Exercise 14</title>
    <meta charset="utf-8">
</head>
<body>
    <h2>PHP Exercises</h2>
    <h3>Exercise 14</h3>
    <form action="#" method="post" id="constant" name="constant">
        <div>
            <label for="text">Grade 1: </label>
    <input type="text" name="grade1" placeholder="Type grade1">
        </div>
        <div>
            <label for="text">Grade 2: </label>
        <input type="text" name="grade2" placeholder="Type grade 2">
        </div>
        <div>
            <label for="text">Grade 3: </label>
        <input type="text" name="grade3" placeholder="Type grade 3">
        </div>
        <div>
      <input type="submit" name="button" id="sending" value="Send">
        </div>
    </form>
    <?php
        if(isset($_POST['button'])){
            $grade1 = $_POST['grade1'];
            $grade2 = $_POST['grade2'];
            $grade3 = $_POST['grade3'];

            while($grade1<0){
                    echo "Error!";
            }

            do{
                if ($grade2<0 | $grade2>20) {
                    echo "Error!";
                }

            }while($grade2>=0 && $grade2<=20);

            do{
                if ($grade3<0 | $grade3>20) {
                    echo "Error!";
                }

            }while($grade3>=0 && $grade3<=20);

            $prom = ($grade1+$grade2+$grade3/3);

            if ($prom>=15) {
                echo "The averages is: " . $prom;
                echo "The student passed the course!";
            }else{
                echo "The averages is: " . $prom;
                echo "The student did not pass the course.";
            }
        }

    ?>
 </body>
</html>
Manuel Sayago
  • 113
  • 1
  • 1
  • 5
  • 2
    Without seeing any code it's impossible to know what problem you have, but reading between the lines it sounds like you have the wrong understanding of programming a web client. See [What is the difference between client-side and server-side programming?](http://stackoverflow.com/q/13840429/476) for starters… – deceze Aug 01 '16 at 14:12
  • I did publish an online file in Google Drive, can't you see it, can you? – Manuel Sayago Aug 01 '16 at 17:43
  • Ready, I edited the post. Now you can see what I'm talking about. Can you tell me a way that I can validate those fields using PHP? I know it is very different than pseint and #C or C++. – Manuel Sayago Aug 01 '16 at 17:47
  • How have you implemented `read grade1` in PHP...? – deceze Aug 01 '16 at 18:40
  • Yes, I used this: `if(isset($_POST['button'])){ $grade1 = $_POST['grade1']; } ` – Manuel Sayago Aug 01 '16 at 20:03
  • And you're doing this in a loop? Then what you first need to understand is HTTP. One HTML `
    ` submission triggers one HTTP request to the server. The `$_POST` isn't going to change unless and until you submit a form again.
    – deceze Aug 01 '16 at 20:25
  • @deceze I put the PHP code. I hope you can check it and help me. Thanks for answering me! I did read what you sent me. The difference here is with PHP I need to emule as if I had a web page and recreate the communication between user and the server. That I'm not sure how to do is validate those fields. I checked online and I saw that I need functions to validate what type of values are received, right? – Manuel Sayago Aug 02 '16 at 01:56

2 Answers2

1

PHP cannot interactively read from a command prompt or other immediately refreshing input. The model of writing server-side code for web clients is always that the web client (browser, HTML) sends one HTTP request containing data, the server evaluates that data, then sends a response. The data is not going to refresh until another HTTP request is made. As such it makes no sense to loop over a $_POST value until it is the correct value; the value won't change during the course of one execution of the code. Your logic must be:

  1. Evaluate each input once.
  2. If any one input is invalid, reject the entire request.
  3. Only if all inputs are valid, do whatever you want to do.
  4. Return an HTML response saying what's wrong or what has succeeded.

Exempli gratia:

<?php

    $errors = [];

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
        if ($_POST['grade1'] < 0) {
            $errors['grade1'] = 'Too low';
        }

        ...

        if (!$errors) {
            // validation successful, do something 
        }
    }

?>

<form method="post">
    <input name="grade1" value="<?= htmlspecialchars($_POST['grade1'] ?? null); ?>">
    <?php if (isset($errors['grade1'])) : ?>
        <span class="error"><?= $errors['grade1']; ?></span>
    <?php endif; ?>
    ...
</form>
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks a lot @deceze I'm going to solve it a put it here, so this could be solved! Is it necessary to used that function htmlspecialchars? Do I have to mix HTML with PHP in that part just because? Or Can I do my PHP things in one part different from HTML? – Manuel Sayago Aug 03 '16 at 20:10
  • Thank you for the explanation of the request/response vis a vis PHP! – YCode Mar 27 '19 at 01:22
1
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Exercise 14</title>
    <meta charset="utf-8">
</head>
<body>
    <h2>PHP Exercises</h2>
    <h3>Exercise 14</h3>
    <form name="exer14" action="#" method="post" id="constant" name="constant">
        <div>
            <label for="text">Grade 1: </label>
            <input type="number" name="grade1" placeholder="Type grade 1"  required>
        </div>
        <div>
            <label for="text">Grade 2: </label>
            <input type="number" name="grade2" placeholder="Type grade 2"  required>
        </div>
        <div>
            <label for="text">Grade 3: </label>
            <input type="number" name="grade3" placeholder="Type grade 3"  required>
        </div>
        <div>
            <input type="submit" name="button" id="sending" value="Send">
        </div>
    </form>
    <?php

    if(isset($_POST['button'])){
        $grade1 = $_POST['grade1'];
        $grade2 = $_POST['grade2'];
        $grade3 = $_POST['grade3'];
        $count = 0;
        $errors = array("Error1" => "Error! The grade $grade1 is invalid. Type a grade between 0 and 20.",
                        "Error2" => "Error! The grade $grade2 is invalid. Type a grade between 0 and 20.",
                        "Error3" => "Error! The grade $grade3 is invalid. Type a grade between 0 and 20.");

        if (empty($_POST['grade1']) || empty($_POST['grade2']) || empty($_POST['grade3'])) {
            echo "Complete all inputs.";

        }elseif (is_numeric($grade1)==false || is_numeric($grade2)==false || is_numeric($grade3)==false) {

            if (is_numeric($grade1)==false) {
                echo "Error! Invalid grade: '$grade1' contains letters. Type a grade between 0 and 20." . "<br>";                   
            }
            if (is_numeric($grade2)==false) {
                echo "Error! Invalid grade: '$grade2' contains letters. Type a grade between 0 and 20." . "<br>";                   
            }
            if (is_numeric($grade3)==false) {
                echo "Error! Invalid grade: '$grade3' contains letters. Type a grade between 0 and 20." . "<br>";                   
            }

        }elseif ($grade1<0 || $grade1>20 || $grade2<0 || $grade2>20 || $grade3<0 || $grade3>20) {

            if ($grade1<0 || $grade1>20){
                echo $errors["Error1"] . "<br>";
            }
            if ($grade2<0 || $grade2>20){
                echo $errors["Error2"] . "<br>";
            }
            if ($grade3<0 || $grade3>20){
                echo $errors["Error3"] . "<br>";
            }
                //print_r($errors);
        }elseif (($grade1>=0 || $grade1<=20) && ($grade2>=0 || $grade2<=20) && ($grade3>=0 || $grade3<=20)) {

            $prom = ($grade1+$grade2+$grade3)/3;

            if ($prom>=15) {
                echo "The student average is " . $prom . "<br>";
                echo "The student passed the course!";
            }else{
                echo "The student average is " . $prom . "<br>";
                echo "The student failed the course.";
            }
        }else{
            echo "Enter the right grades.";
        }
    }
    ?>
</body>

I have solved the exercise in this way. I could validate those inputs with several cases, letters and number range. This exercise is really easy but I did it in Pseint and C++ so those are very different from PHP. I understand now what the server client is about.

Manuel Sayago
  • 113
  • 1
  • 1
  • 5