-1

I have this PHP code:

<?php
    $score11 = $_POST['passmarks12'];

    if($_POST['passmarks12'] > 100){
        $grade11 = "";
    }
    elseif ($_POST['passmarks12'] < 45){
        $grade11 = "Fail";
    }
    $strg = " $grade11";

    echo $strg;

?>

The code is always printing "Fail" regardless of what is sent in.

I want it so that if it passes in blank or invalid input it fails.

And how should I properly cleanse the input?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
user2260431
  • 75
  • 1
  • 3
  • 14

4 Answers4

1

Try this:

<?php

    //$_POST['passmarks12'] = '';

    if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
    {
        $grade11 = "";
    }

    else if ($_POST['passmarks12'] < 45){

        $grade11 = "Fail";
    } else{
            $grade11 = "Pass";
    }
    $strg = " $grade11" ;

    echo $strg;

    ?>
Vijaya Pandey
  • 4,252
  • 5
  • 32
  • 57
1

Points:

  1. Check if $_POST['key'] exists using isset.
  2. Check if $_POST['key'] has a valid data type, string.
    It may come as array.
  3. Check if $_POST['key'] has a valid numeric format.
  4. Compare $_POST['key'](String) and 45(Integer), using intval.

Example:

<?php

switch (true) {

    case !isset($_POST['passmarks12']):
    case !is_string($score = $_POST['passmarks12']):
    case !is_numeric($score):
        $result = 'Error (Invalid parameter)';
        break;
    case (intval($score) < 45):
        $result = 'Fail (Less than 45)';
        break;
    default:
        $result = 'Success (No less than 45)';

}

echo $result;
mpyw
  • 5,526
  • 4
  • 30
  • 36
0

I think you want

elseif ($_POST['passmarks12'] < 45 && !empty($_POST['passmarks12']))
  • 1
    Those should be the other way around, otherwise you get an error if `$_POST['passmarks12']` isn't set. – rpkamp May 19 '13 at 08:52
-1

This PHP code will make sure $_POST is not empty before comparing it to 100.

<?php
    $score11 = $_POST['passmarks12'];

    if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
        $grade11 = "";

    elseif ($_POST['passmarks12'] < 45)
        $grade11 = "Fail";

    $strg = " $grade11" ;

    echo $strg;

?>
Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Meeran
  • 77
  • 2