/    Sign up×
Community /Pin to ProfileBookmark

PHP form-Search script to search text file, find match

Hi, very new to PHP and I may be on the right track with this or totally lost.

[LIST]

  • [*]

    From my index.php form, a user will enter their name, and a number associated to them, both in input boxes.


  • [*]

    They will then select from a drop down list a course they want to take.


  • [*]

    Once they hit the submit button I need to take their name to see if they are already enrolled and if the class is at it’s max capacity.


  • [*]

    The student info is in student.txt ie Mike Wazowski?X-68-524 (student name and number).


  • [*]

    The course info is in course.txt ie Animation Film Design:AFD-250:6 (course name and number and max capacity).


  • [*]

    The search will be in enrollment.txt ie Buzz Lightyear?X-34-121:Visual Effects:VE-298.


  • [*]

    The code I have is towards the bottom of the PHP and before the HTML starting with $datafile = ‘student.txt’;


  • [/LIST]

    Thank you.

    [code=php]<?php
    ini_set(‘display_errors’, 1);
    error_reporting(E_ALL);

    // Define and set variables
    $msg = ”;
    $submit = isset($_POST[‘submit’]) ? $_POST[‘submit’] : NULL;
    $student = ”;
    $studentname = isset($_POST[‘studentname’]) ? $_POST[‘studentname’] : NULL;
    $studentnumber = isset($_POST[‘studentnumber’]) ? $_POST[‘studentnumber’] : NULL;
    $coursefile = ‘course.txt’;
    $enrollfile = ‘enrollment.txt’;
    $in = fopen ($coursefile, ‘r’) or die (“course.txt cannot be opened for reading.”);

    // Sanitization and Validation coding
    if($submit)
    {
    $student = ”;
    $studentfile = ‘student.txt’;
    $course = isset($_POST[‘course’]) ? $_POST[‘course’] : NULL;
    $coursename = ”;
    $coursenumber = ”;
    $coursemax = 0;

    if ($submit)
    {
    $studentname = $_POST[‘studentname’];
    $studentnumber = $_POST[‘studentnumber’];
    }

    if ($studentname)
    {
    $studentname = strip_tags ($_POST[‘studentname’]);
    $studentname = htmlentities ($_POST[‘studentname’]);
    $studentname = trim($_POST[‘studentname’]);

    }

    if ($studentnumber)
    {
    $studentnumber = strip_tags ($_POST[‘studentnumber’]);
    $studentnumber = htmlentities ($_POST[‘studentnumber’]);
    $studentnumber = trim($_POST[‘studentnumber’]);
    }

    if ($course)
    {
    $course = strip_tags ($_POST[‘course’]);
    $course = htmlentities ($_POST[‘course’]);
    }

    // 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

    //$file_handle = fopen(‘enrollment.txt’, “r”);
    //while (!feof($file_handle))
    //{
    //$line_of_text = fgets($file_handle);
    //echo $line_of_text . “<BR>”;
    //}

    //fclose($file_handle);

    //$file = ‘course.txt’;
    //$FH = fopen ($file, ‘r’) or die (“$file cannot be opened for reading.”);
    //while ($line = fgets ($FH)) {
    //echo $line;
    //echo “<br>n”;
    //}
    //fclose ($FH);

    //**********THIS IS THE CODE AND PROCESS IN QUESTION*********
    $datafile = ‘student.txt’;
    // If selection has been made, find a match

    if (isset ($_POST[‘studentname’])) {
    $student = htmlentities ($_POST[‘studentname’]);
    $DB = fopen ($datafile, ‘r’) or die (“$datafile cannot be opened for reading.”);
    $found = FALSE;
    while ($record = fgets ($DB) and ! $found) {
    $field = explode (“:”, htmlentities (trim ($record)));
    $found = $student === $field[0];
    }
    fclose ($DB);
    if ($found) {
    echo “<p>$field[0] $field[1]</p>n”;
    }
    }

    $DB = fopen ($enrollfile, ‘r’) or die (“$enrollfile 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);
    //**************************************************************

    // ND @ Webdeveloper.com
    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>’;
    }
    }

    ?>
    <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 & last name using this format: Dash Parr” 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 this format: PX-03-046″ tabindex=”20″ size=”50″></dd>
    <br>
    <?php echo $msg; ?>
    </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>[/code]

    to post a comment
    PHP

    10 Comments(s)

    Copy linkTweet thisAlerts:
    @NogDogMar 15.2016 — Frankly -- and I realize this is probably not of your doing -- the whole idea of doing this via a bunch of text files is kind of silly. It's trying to use them as a database, which would be so much easier with ... you guessed it: a database. A DB would also be faster and would scale much, much better as the amount of data grew. (A DB would also take care of locking issues to help prevent race conditions which otherwise would have to be handled with file-locking stuff.)

    So, if someone held a gun to my head and said I had to complete that assignment using those text files, I'd probably launch an in-memory instance of an SQLite DB, read the data files in and insert them into relevant tables in the DB, do all the data processing using SQL, then write the changed data back into the relevant files -- just to show the person assigning this to me how silly I think it is. ?
    Copy linkTweet thisAlerts:
    @NogDogMar 15.2016 — So, if you're stuck reading stuff from a file, you could generalize that activity using the function below to read it into an array:
    [code=php]
    <?php

    /**
    * Read a delimited text file into an array
    *
    * @param string $file
    * @param array $columns to be used as array keys
    * @param string $separator
    * @return array|bool
    */
    function parseFile($file, Array $columns, $separator=',')
    {
    $fh = fopen($file, 'r');
    if($fh == false) {
    return false;
    }
    $data = array();
    $numColumns = count($columns);
    while(($row = fgetcsv($fh, null, $separator)) != false) {
    if(count($row) == $numColumns) {
    $data[] = array_combine($columns, $row);
    }
    }
    return $data;
    }


    // let's try it out

    // create a test file:
    $text = <<<EOD
    red:cherry:sweet
    yellow:lemon:sour
    green:apple:tart
    ignorethisline
    EOD;
    file_put_contents('test.txt', $text);

    // use the function to read that file into an array
    $dataArray = parseFile('test.txt', array('color', 'fruit', 'flavor'), ':');

    // let's see what we got:
    echo "<pre>";
    print_r($dataArray);
    echo "</pre>";

    // clean up after ourselves:
    unlink('test.txt');
    [/code]


    PS: The idea here is that you define that function once, then every time you need to read one of those text files, you just call the function with the applicable arguments.
    Copy linkTweet thisAlerts:
    @BlondieCauthorMar 15.2016 — Frankly -- and I realize this is probably not of your doing -- the whole idea of doing this via a bunch of text files is kind of silly. It's trying to use them as a database, which would be so much easier with ... you guessed it: a database. A DB would also be faster and would scale much, much better as the amount of data grew. (A DB would also take care of locking issues to help prevent race conditions which otherwise would have to be handled with file-locking stuff.)

    So, if someone held a gun to my head and said I had to complete that assignment using those text files, I'd probably launch an in-memory instance of an SQLite DB, read the data files in and insert them into relevant tables in the DB, do all the data processing using SQL, then write the changed data back into the relevant files -- just to show the person assigning this to me how silly I think it is. ?[/QUOTE]


    Oh NogDog - this made me laugh and I agree with you about the database. I just looked at week 11 notes which is next week and it starts with "Introducing SQL" and goes from there but will only be the tip of the MySQL iceberg. I have a test next Monday on session security issues so between working on week 10 this week and reading week 11 for next week I need to get ready for the test and keep on working on this index.php form - and work. Thanks for the laugh and for the additional explanation and "How To" - I will be tackling it after work.
    Copy linkTweet thisAlerts:
    @LeeLee21Nov 01.2018 — @BlondieC#1464563

    You have to tell me how this code worked out for you ???? I am in this course now, and the instruction is horrible! You are the only one who has posted anything that explains how to set this up and run it so it will work! And I am beyond grateful!

    I am interested in how you made the code run through the enrollment file? I am a visual learner, and have been running your code to see how it displays and works. It has been a great help, and any additional help here would be greatly appreciated!

    Thank you in advance!
    Copy linkTweet thisAlerts:
    @MasoknfNov 02.2018 — Thanks for this code!
    Copy linkTweet thisAlerts:
    @ginerjmNov 03.2018 — You're saying "Thanks" for code that the rest of the posts here tell you quite bluntly that it is NOT the way to do it?

    Besides the fact that this post is over 2 years old
    Copy linkTweet thisAlerts:
    @vir1tNov 08.2018 — 
    idea is not bad
    Copy linkTweet thisAlerts:
    @ginerjmNov 08.2018 — What idea exactly are you talking about? Remember - AS HAS BEEN POINTED OUT - this info is 2 years old
    Copy linkTweet thisAlerts:
    @John777RJun 10.2023 — This is also relevant for me, because I recently started learning PHP
    Copy linkTweet thisAlerts:
    @John777RJun 12.2023 — I also wanted to add that such scenarios do not always support the action algorithm. That is, the link should be in the code, and during training you should use best ghost writer services. This will help to reach a certain compromise and coordination of the learning process. And it will save your nerves and time.
    ×

    Success!

    Help @BlondieC spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 4.23,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,

    tipper: @Samric24,
    tipped: article
    amount: 1000 SATS,
    )...