Jump to content

Won't read my text file


belbin09

Recommended Posts

My code works fine for the most part, unfortunately though it doesn't seem to be reading the student.txt file. If one student is registered for a course it doesn't let anyone else register for the same course.

<?php

$students = "student.txt"; // text file for students and student number
$reg = "load.txt";

//converting a string into a variable

$name = $_POST["name"];
$number = $_POST["snumber"];
$course = $_POST["pcourse"];

//open student file and explode into an array



$found = 0;

// turning students into an array to read

$fileHandle = fopen($students, "r") or die ("Student file does not exist");

while($line=fgets($fileHandle))
{
  $drop = explode(',',$line);

  if($name==$drop[0]&&$number == trim($drop[1])) //trip to remove whitespace in student number
  {
    $found = 1;
    break; // break if found
  }
}

fclose($fileHandle);
$toRep="";

if($found==1)
{
  $fileHandle = fopen("course.txt", 'r');
  while($line=fgets($fileHandle))
  {
    $drop = explode('||',$line);

    if($drop[1]==$course)
    {
      $found = 2;  // course found
      if($drop[2]>0)
      {
        $found = 3;       // couse has seats  
        $toRep= $line;
        break;
      }
    }

  }
}
else
{
  echo "Student could not be found.";
  die();
}



if($found ==1)
{
  echo "The course cannot be found";
  die();
}

if($found==2)
{
  echo "The course is full";
  die();
}


if($found==3)
{
  $loadHandle = fopen("load.txt",'r'); 
  while($line = fgets($loadHandle))
  {
    $drop = explode(',', $line);

    if(trim($drop[1])==$course)
    {
      echo "You have already registered for the course.";
      die();
    }
  }
}

$loadHandle2 = fopen("load.txt", 'a');

fwrite($loadHandle2,"$name,$course\n");

fclose($loadHandle2);
fclose($loadHandle);

$courseHandle = fopen('course.txt', 'r');
$whole = file_get_contents('./course.txt');// read the whole file

$drop = explode('||', $toRep);


$count = (int)$drop[2];
$count = $count - 1; // make one seat less

$newStr = $drop[0]."||".$drop[1]."||".$count."\n";  // make a new string with new seat count

$whole =str_replace($toRep, $newStr, $whole); // replace the old text with new


$courseHandle2 = fopen('course.txt', 'w');
fwrite($courseHandle2, $whole); // overwrite the entire file.

echo "Sucessfully Enrolled."

?>
Link to comment
Share on other sites

if your goal is to test if a student is registered for a class, wouldn't you logic need to test both the student number and the class number? you are only testing the class number and it's starting to look to us, like you are not even looking at and thinking about what your code is doing.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.