Reading a text file and only writing if the string doesn't exist in the file

Hi, I am new to PHP and trying to finish an assignment. I am creating a course registration. Index.php is my main page and displays my form where if asks for the students name, number and from a drop down, which reads the course from a text file, selects a course. Then in enrolled.php using r I am to read the load.txt, which is blank and check if the student is already enrolled in the course. If they are I do not want the student or the course to append to load.txt. So far my code is just printing that the student is already registered for the course and then printing the student number and the course. How can I fix this?

[php]<?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

$sfile = fopen($students, ‘r’) or die (“Student file does not exist”);

$found = 0;

// turning students into an array to read

while ($sline = fgets ($sfile)) {
$list = explode(",",trim($sline));

//test array against text input

if ($name == $list[0] && $number == $list[1]) {

$found = 1;

//load number and course selected into load.txt;

$handle = fopen ($reg, 'r');
  while ($loadf = fgets ($handle)) {
  $data = explode (',', trim($loadf));

fclose ($handle);

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

  fwrite ($handle, "$name, $course\r\n");

fclose ($handle);

include 'load.txt';

break;

} // end of if 34

} // end of while

if (!$found) {

include ‘index.php’;
}

fclose($sfile);

?>
[/php]

Well, you could always start with the answers you were already given where you cross posted this.
https://forums.phpfreaks.com/topic/305626-while-and-if-statements/

Sponsor our Newsletter | Privacy Policy | Terms of Service