Jump to content

While and if statements


belbin09

Recommended Posts

My working code looked like this: 

  <?php

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

  //converting a string into a variable

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

  $coursedata = "course.txt"; // text file coursedata
  $cfile = fopen ($coursedata, 'r');

  while ($line = fgets ($cfile)) {
    $drop = explode ('||', trim ($line));

  } // end of course while

    fclose ($cfile);

  //open student file and explode into an array

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

  $found = 0;

  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 ('load.txt', 'a');
      fwrite($handle, "$number, $drop[1] \n");
      fclose($handle);

      include 'load.txt';

      break;

  } 

  } // end of while

  if (!$found) {

    include 'index.php';

  } // end of found i

  fclose($sfile);

  ?>

When the user entered in their name, student name and selected a course it would take them to the code listed about. Then I was able to get the code to write the student number and the course code into a text file called load.php and load that to enrolled.php. So my next step was to get it so that way the same student couldn't register for a course they are already enrolled in. However when I entered in the code below it wouldn't display anything. Anyone have any suggestions?

  <?php

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

  //converting a string into a variable

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

  $coursedata = "course.txt"; // text file coursedata
  $cfile = fopen ($coursedata, 'r');

  while ($line = fgets ($cfile)) {
    $drop = explode ('||', trim ($line));

  } // end of course while

    fclose ($cfile);

  //open student file and explode into an array

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

  $found = 0;

  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 ('load.txt', 'a');

      while ($loadf = fgets ($handle)) {
        $data = explode (',', $loadf);

          if ($number == $data[0] && $drop[1] != $data[1]) {

              fwrite($handle, "$number, $drop[1] \n");

        } elseif ($number == $data[0] && $drop[1] == $data[1]) {

          echo  "Student is already registered for this course";

        } //end of else if

      include 'load.txt';

      break;

    } // end of while

    fclose($handle);

  } // end of if

  } // end of while

  if (!$found) {

    include 'index.php';

  } // end of found i

  fclose($sfile);

  ?>
Link to comment
Share on other sites

actually, those silly line numbers don't copy/paste, when i just tried it, through you do get an extra space before each resulting line.

 

even if you are required to use text files, your code needs to be organized and use the least amount of program logic to accomplish any particular task.

 

since you would only use text files for a small amount of data, you should use file(), with the second parameter set to FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES, to read all the lines of any file into an array using a single statement. doing this will probably help fix your current problem, because you are looping over all the lines in the course.txt file, and only keeping the data from the last line.

 

if you want to append a line to a file, use file_put_contents(), with the third parameter set to - FILE_APPEND

 

your post method form processing code needs to detect if a post method form was submitted before running any of the form processing code. use - if($_SERVER['REQUEST_METHOD'] == 'POST'){ all the form processing code goes here...}

 

if you are searching and displaying data, you would a get method form. if you are creating/modifying data, you would use a post method form.

 

since a student's student number should be unique, there's no good reason to enter both the name and number. just enter the number or even better, since all students must be in the student.txt file before they can pick a course, produce a select/option menu from the data in student.txt, and pick the student, rater then type any data in. or even better yet, a student must be logged in before they register for a course. the login code would store the user's id/student-number in a session variable, you would just use this to get the student number. you would make a select/option menu form the course.txt data to select a course to register for.

 

you need to define what inputs you have, what processing you are doing to do, and what result you are going to produce and with what data structure,  ... before you write any code. this will help you write better and simpler code. i/we currently don't know what the purpose or structure of the data in the load.txt file is.

 

after you define what the processing is going to be, you can break that processing down into the steps needed. then write the code that implements each step.

 

the code in your file should be laid out in this general order -

 

1) initialization - common code that the rest of the application code needs. define/require setting and configuration values, functions, class auto-loader, start session, create database connection
 
2) get any user permissions - user permissions will be used through the remainder of the code to control what the user can do or see
 
3) post method form processing code - detect and process any $_POST data
 
4) get method business logic - get/produce data that will be used to display the page
 
5) html document/template - produce the actual html document, using any output from the above items
 
your course.txt data should hold the total number of seats, not the remaining. you should calculate the remain seats by getting the total and subtracting the number that are signed up for. this will prevent coding errors from irrevocably altering the course.txt data.
 
the data file holding the course/student registration should only hold the course id and the student number.
 
an easier way to find if data is already in an array, rather then to loop over the array, splitting and comparing each element against the new data, is to take the new data you are trying to find, produce a sting in the exact same format as what is stored in the array, then just use in_array() to find if the new value is already in the array.
Edited by mac_gyver
Link to comment
Share on other sites

further thing(s) about your code or what you should be doing -

 

1) inside the post method form processing code, you need to validate the inputs first, then if there are no validation errors, use the submitted data. you should use a php array variable to hold the validation errors. this same variable will be an error flag. if the array is empty, there are no errors. if the array is not empty, there are errors. you can display the contents of this array variable in the appropriator place in your html document to display the errors.

 

2) I'm wondering what the purpose of the following code is (which i just copied/pasted without the line numbers) - 

  $coursedata = "course.txt"; // text file coursedata
  $cfile = fopen ($coursedata, 'r');

  while ($line = fgets ($cfile)) {
    $drop = explode ('||', trim ($line));
  } // end of course while
    fclose ($cfile);

what i suspect it is supposed to be doing is validating the submitted course number. what it is doing is getting the last line from the course.txt file, that's being used later in some code where nothing about the course.txt file makes any logical sense. this is where defining things before you write any code will help.

Link to comment
Share on other sites

Still off topic but keeping those interested up to date.

 

While I did switch to Chrome for a couple of months recently, I finally went back to IE. Found it horribly frustratingly slow. So my current situation is when I select the OP's code above Ie does not highlight the line numbers but when I hit paste they do come across. Now that's strange behavior! And it pasts the same way in my IDE as well as two text editors.

Link to comment
Share on other sites

 

2) I'm wondering what the purpose of the following code is (which i just copied/pasted without the line numbers) - 

  $coursedata = "course.txt"; // text file coursedata
  $cfile = fopen ($coursedata, 'r');

  while ($line = fgets ($cfile)) {
    $drop = explode ('||', trim ($line));
  } // end of course while
    fclose ($cfile);

what i suspect it is supposed to be doing is validating the submitted course number. what it is doing is getting the last line from the course.txt file, that's being used later in some code where nothing about the course.txt file makes any logical sense. this is where defining things before you write any code will help.

 

 

If that line is from enrolled.php its because I was trying to access the course.txt file from index.php

Link to comment
Share on other sites

 

since you would only use text files for a small amount of data, you should use file(), with the second parameter set to FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES, to read all the lines of any file into an array using a single statement. doing this will probably help fix your current problem, because you are looping over all the lines in the course.txt file, and only keeping the data from the last line.

 

 Hi my teacher hasn't actually taught us how to use file( ) or FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES. He has only shown us how to use fopen, fgets and explode statements. How exactly would file( ) change my code?

Link to comment
Share on other sites

I"ll jump in now.

 

Looking at your original code you read the course file in a while loop. But - the problem there is that you read the whole file, line by line and only save the last record (in your '$drop' variable). Don't you want to actually do something with each line that you read in? Your while loop is good for doing a process repeatedly. So - add the necessary logic INSIDE the while loop, after you have the $drop variable for the current line and accomplish your task for the courses.

 

Don't know what else you are trying to do there, but at least this may help you realize how to read a file and do things with it.

Link to comment
Share on other sites

How exactly would file( ) change my code?

 

 

have you looked at the php.net documentation for the function? it shows what input parameters it takes and what data is returned by the function.

 

it will change your code from having multiple statements just to open and read through the file, into to a single line of code to get the contents of the file into an array variable. once you have the contents of a file in an array variable, you can easily search for values in the array or you can loop over the array using a foreach(){} loop.

 

the last paragraph in reply #5 states how you can simply find if a value is in the array, so finding if the student number and course number is already in the data will be just one line of code.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.