PHP form-calling function failing to work properly

I have my index.php form and if a valid student name and student number are entered I’d like “Student name and number are valid.” to be echoed.

I have validated the student names and student numbers. However, even when entering a valid student name and student number the message echoed is “The information you have entered is not valid. Please enter your information again.”

I’m calling the function validateStudent but I must be calling it in the wrong place or incorrectly. This function is called towards the end of the PHP scrip and just before the HTML starts. Thank you.

<?php 
ini_set('display_errors', 1); 
error_reporting(E_ALL); 

// Define and set variables 
$student = ""; 
$studentname = ""; 
$studentnumber = ""; 
$studentfile = "student.txt"; 
$course = "";
$coursename = ""; 
$coursenumber = ""; 
$coursemax = 0;
$coursefile = "course.txt"; 
$in = fopen ('course.txt', 'r') or die ("course.txt cannot be opened for reading."); 

// Sanitization and Validation coding will go here 
if (isset($_POST['submit'])) { 
    $studentname = $_POST['studentname']; 
    $studentnumber = $_POST['studentnumber']; 
} 

if (isset($_POST['studentname'])) {
    $studentname = strip_tags ($_POST['studentname']); 
    $studentname = htmlentities ($_POST['studentname']); 
}

if (isset($_POST['studentnumber'])) {
    $studentnumber = strip_tags ($_POST['studentnumber']);
    $studentnumber = htmlentities ($_POST['studentnumber']); 
}

if (isset($_POST['course'])) {
    $course = strip_tags ($_POST['course']);
    $course = htmlentities ($_POST['course']); 
}

//$studentname = trim($_POST['studentname']);

//$studentnumber = trim($_POST['studentnumber']);


// Validate student name/number against text file  
function validateStudent($studentName, $studentNumber) 
{ 
    $found = false; 
    $fh = fopen('student.txt', 'r'); 
    while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1) { 
            if($line[0] == $studentName and $line[1] == $studentNumber) { 
                $found = true; 
                break; 
            } 
        } 
    } 
    return $found; 
} 

// Validate course name/number against text file 
function validateCourse($courseName, $courseNumber, $courseMax) 
{ 
    $found = false; 
    $fh = fopen('course.txt', 'r'); 
    while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1) { 
            if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) { 
                $found = true; 
                break; 
            } 
        } 
    } 
    return $found; 
} 


//$DB = fopen ($coursefile, 'r') or die ("$coursefile cannot be opened for reading.");
 //while ($record = fgets ($DB) ) {
    //$field = explode (":", htmlentities (trim ($record)));
    //echo "<option value=\"$field[1]\">$field[0] $field[1] $field[2]</option>\n";
 //}
 //fclose ($DB);
 

if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
            validateStudent($_POST[$studentname], $_POST[$studentnumber]);
            echo 'Student name and number are valid.\n';
        }
        else {
            echo '<p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">**The information you have entered is not valid.  Please enter your information again.**</p>';
        }

  
?> 
<html> 
<head> 
    <title>Registration Form</title> 
    <style> 
        body{background-color: #ffffe6; width:610px;} 
        h1 {color: #29a3a3;} 
        .inputbox {padding: 7px; border: #FF9966 1px solid; border-radius: 4px;} 
        .btn {padding: 10px; background-color: #29a3a3; border: solid 1px #FF9966; border-radius: 4px; color: #FFFFFF; font-weight: bolder; cursor: pointer;} 
    </style> 
</head> 
<body> 
<h1>Course Registration</h1> 
<form method="post" action="index.php"> 
    <fieldset><legend><strong>Student Information</strong></legend> 
        <dl> 
            <dt>Student Name:</dt> 
            <dd><input class="inputbox" name="studentname" type="text" id="studentname" value='<?php echo htmlentities($studentname) ?>' required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd> 
            <br> 
            <br> 
            <dt>Student Number:</dt> 
            <dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value='<?php echo htmlentities($studentnumber) ?>' required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd> 
        </dl> 
        <br> 
    </fieldset> 
    <br> 
    <fieldset><legend><strong>Course Selection</strong></legend> 
        <br> 
        Select a Course:<select name="course" tabindex="30">\n"; 
            <option value="-1" >Available Courses...</option> 
                <?php 
                while(($fields = fgetcsv($in, null, ':')) != false) { 
                    if (count($fields) > 1) { 
                        echo " 
                            <option value=\"$fields[1]\">$fields[0] $fields[1]</option>"; 
                    } 
                } 
                ?> 
        </select> 
        <br> 
        <br> 
        <br> 
        <br> 
        <br> 
        <br> 
    </fieldset> 
    <div> 
        <p> 
            <input name="reset" type="reset" tabindex="40" value="Clear Form" class="btn"> 
            <input name="submit" type="submit" tabindex="50" value="Submit Form" class="btn"> 
        </p> 
    </div> 
</form> 
</body> 
</html>

Try this:

// DEFAULT FAILED MESSAGE
$msg = '
  <p style="color: red; text-align: center; font-size: 15px; font-weight: bold;">
    **The information you have entered is not valid.  Please enter your information again.**
  </p>';
if (isset ($_POST[$studentname], $_POST[$studentnumber])) {
  validateStudent($_POST[$studentname], $_POST[$studentnumber]);
  $msg = 'Student name and number are valid.\n';
  // \n ONLY works inside double quotes
  $msg = "<p>Student name and number are valid.\n</p>"; 
}
...
...
<body> 

<?php echo $msg; ?>

<h1>Course Registration</h1> 
...
...

Hi John, really like the $msg - thank you! Here’s how I put everything together and placed the <?php echo $msg; ?> down in the body under the second input box. Looks much better! One question - when index.php loads the failed message is already displayed because at this time both input boxes are empty. Is there any way of having not display until after there is input in the input boxes?

<?php

if( isset( $studentname, $studentnumber)) {
  $valid = validateStudent($studentname, $studentnumber);
  if ($valid) {
    $msg = '<p style="color: black; text-align: left; font-size: 15px; font-weight: bold;">Thank you.</p>';
  }else
    $msg = '<p style="color: red; text-align: left; font-size: 15px; font-weight: bold;">**The information you have entered is not valid.  Please enter your information again.**</p>';
}

?>
1 Like

Many thanks, glad I was able to help.

I prefer this method which should also be faster to display because there is no need to load some PHP script until the student has entered their name, course, etc.

Check to see if the $_POST['variable'] is set. If it is not set then a NULL value is set which can be tested if true or false:

// Define and set variables 
$msg            = ''; // DEFAULT TO PREVENT ERROR  
$submit         = isset($_POST['submit']) ? $_POST['submit'] : NULL;
$coursefile     = 'text.txt'; // "course.txt"; 
$in             = fopen ($coursefile, 'r') or die ("course.txt cannot be opened for reading."); 

if($submit) 
{
  $student        = ""; 
  $studentname    = isset($_POST['studentname'])   ? $_POST['studentname']   : NULL; 
  $studentnumber  = isset($_POST['studentnumber']) ? $_POST['studentnumber'] : NULL;
  $studentfile    = "student.txt"; 
  $course         = isset($_POST['course']) ? $_POST['course'] : NULL;
  $coursename     = ""; 
  $coursenumber   = ""; 
  $coursemax      = 0;

  // Sanitization and Validation coding will go here 
  if ( $submit ) // isset($_POST['submit']))
  { 
      $studentname   = $_POST['studentname']; 
      $studentnumber = $_POST['studentnumber']; 
  } 

  if ( $studentname ) // isset($_POST['studentname']))
  {
      $studentname = strip_tags ($_POST['studentname']); 
      $studentname = htmlentities ($_POST['studentname']); 
  }

  if ( $studentnumber ) // isset($_POST['studentnumber']))
  {
      $studentnumber = strip_tags ($_POST['studentnumber']);
      $studentnumber = htmlentities ($_POST['studentnumber']); 
  }

  if ( $course ) //  isset($_POST['course']))
  {
      $course = strip_tags ($_POST['course']);
      $course = htmlentities ($_POST['course']); 
  }

  //$studentname = trim($_POST['studentname']);
  //$studentnumber = trim($_POST['studentnumber']);

  // Validate student name/number against text file  
    function validateStudent($studentName, $studentNumber) 
    { 
      $found = false; 
      $fh = fopen('student.txt', 'r'); 
      while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1)
        { 
          if($line[0] == $studentName and $line[1] == $studentNumber)
          { 
            $found = true; 
            break; 
          } 
      } 
    } 
    return $found; 
  } 

  // Validate course name/number against text file 
    function validateCourse($courseName, $courseNumber, $courseMax) 
    { 
      $found = false; 
      $fh = fopen('course.txt', 'r'); 
      while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1) { 
          if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) { 
            $found = true; 
            break; 
          } 
        } 
      } 
      return $found; 
    } 
}//endif submit

What a difference from mine! I can see the logic to this and I like how you align things as it makes it much, much easier to read.

The only glitch that appeared is the Student Name input box now displays this:
Notice: Undefined variable: studentname in C:\Users\HP Pavilion\XAMPP\htdocs\index.php on line 149
and the Student Number input box now displays this:
Notice: Undefined variable: studentnumber in C:\Users\HP Pavilion\XAMPP\htdocs\index.php on line 153
.

Lines 149 and 153 are in the in the and what displays in the input box (as noted above), overrides the PHP I have in the vlalue=

I think I’m messing up how to do the tags to have the PHP code display on this site properly. Currently the code for the two input boxes is:

<?php 
<form method="post" action="index.php"> 
    <fieldset><legend><strong>Student Information</strong></legend> 
        <dl> 
            <dt>Student Name:</dt> 
            <dd><input class="inputbox" name="studentname" type="text" id="studentname" value='<?php echo htmlentities($studentname) ?>' required autofocus placeholder="Please enter your first and last name" tabindex="10" size="50"></dd> 
            <br> 
            <br> 
            <dt>Student Number:</dt> 
            <dd><input class="inputbox" name="studentnumber" type="text" id="studentnumber" value='<?php echo htmlentities($studentnumber) ?>' required placeholder="Please enter using the following format: PX-03-046" tabindex="20" size="50"></dd> 
            <br>
            <?php echo $msg; ?>
        </dl> 
        <br> 
    </fieldset> 
?>
1 Like

Whoops, sorry about that :frowning:

I formatted your original script to use a strict Doctype and remmed the $studentname and strudentnumber.

Try setting defalt strings to both:

# Define and set variables && DEFAULTS TO PREVENT ERRORS  
  $msg            = ''; 
  $studentname    = '';
  $studentnumber  = '';
  $submit         = isset($_POST['submit']) ? $_POST['submit'] : NULL;
  $coursefile     = "course.txt"; 
  $in             = fopen ($coursefile, 'r') or die ("course.txt cannot be opened for reading."); 


When I change the code to your last post I receive this message: Fatal error: Call to undefined function validateStudent() in C:\Users\HP Pavilion\XAMPP\htdocs\index3.php on line 127

<?php if( isset( $studentname, $studentnumber)) {
  $valid = validateStudent($studentname, $studentnumber); //***THIS IS LINE 127
  if ($valid) {
    $msg = '<p style="color: black; text-align: left; font-size: 15px; font-weight: bold;">Thank you.</p>';
  }else
    $msg = '<p style="color: red; text-align: left; font-size: 15px; font-weight: bold;">**The information you have entered is not valid.  Please enter your information again.**</p>';
}
?>

I have to leave for work but will go over it again when I get home. Thank you!

<?php 
ini_set('display_errors', 1); 
error_reporting(E_ALL); 

// Define and set variables 
$msg            = ''; // DEFAULT TO PREVENT ERROR  
$studentname    = '';
$studentnumber  = '';
$submit         = isset($_POST['submit']) ? $_POST['submit'] : NULL;
$coursefile     = "course.txt"; // "course.txt"; 
$in             = fopen ($coursefile, 'r') or die ("course.txt cannot be opened for reading."); 

if($submit) 
{
  $student        = ''; 
  $studentname    = ''; 
  $studentnumber  = '';
  $studentfile    = 'student.txt'; 
  $course         = isset($_POST['course']) ? $_POST['course'] : NULL;
  $coursename     = ''; 
  $coursenumber   = ''; 
  $coursemax      = 0;

  // Sanitization and Validation coding will go here 
  if ( $submit ) // isset($_POST['submit']))
  { 
      $studentname   = $_POST['studentname']; 
      $studentnumber = $_POST['studentnumber']; 
  } 

  if ( $studentname ) // isset($_POST['studentname']))
  {
      $studentname = strip_tags ($_POST['studentname']); 
      $studentname = htmlentities ($_POST['studentname']); 
  }

  if ( $studentnumber ) // isset($_POST['studentnumber']))
  {
      $studentnumber = strip_tags ($_POST['studentnumber']);
      $studentnumber = htmlentities ($_POST['studentnumber']); 
  }

  if ( $course ) //  isset($_POST['course']))
  {
      $course = strip_tags ($_POST['course']);
      $course = htmlentities ($_POST['course']); 
  }

  //$studentname = trim($_POST['studentname']);
  //$studentnumber = trim($_POST['studentnumber']);

  // Validate student name/number against text file  
    function validateStudent($studentName, $studentNumber) 
    { 
      $found = false; 
      $fh = fopen('student.txt', 'r'); 
      while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1)
        { 
          if($line[0] == $studentName and $line[1] == $studentNumber)
          { 
            $found = true; 
            break; 
          } 
      } 
    } 
    return $found; 
  } 

  // Validate course name/number against text file 
    function validateCourse($courseName, $courseNumber, $courseMax) 
    { 
      $found = false; 
      $fh = fopen('course.txt', 'r'); 
      while(($line = fgetcsv($fh, null, ':')) != false) { 
        if(count($line) > 1) { 
          if($line[0] == $courseName and $line[1] == $courseNumber and $line[2] == $courseMax) { 
            $found = true; 
            break; 
          } 
        } 
      } 
      return $found; 
    } 
}//endif submit
?>

I was able to get it functioning. Thank you so much! :grinning:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.