skip to Main Content

I am working on a project where my script needs to allow the staff to enter a performer/band name into a form and see the correct corresponding phone number when the form is submitted.

The text file I have been given is as follows:

Spiders 0392848271
TheBESTband 0482947291
Lauren 0382718319
Queen 0482827183
KateIsland 0373829420
Reposessed 0472478292
HighRollers 0289428372
Mindstorm 0347287492
WhirlyBirds 0272729193
Traceylyly 0303828294

I have already written the code to parse the text file and store the values into an associative array, but I need to know how to get input from the form and match it to the the associative array and print the corresponding phone number.

<?php

$filename = "performers.txt";
$myfile = fopen($filename, "r") or die("Unable to open file!");

$content = array();
while(!feof($myfile)) {
    $content[] = fgets($myfile); 
}

fclose($myfile);

$data = array();
foreach($content as $line) {
    $pieces = explode(' ', $line);
    $data[trim($pieces[0])] = trim($pieces[1]);
}

foreach ($data as $name => $phoneno) {
    if (isset($_POST['performer']))
    {
        $performer = $_POST['performer'];
        foreach ($data as $name => $phoneno)
        {
            if ($name == $performer)  
            {
                echo $phoneno;
            }
        }
    }
}

My html coding:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
</head>
<body>
    <h1>Melbourne Performance Hall <br> Performer Phonebook </h1>
    <p> Enter the performer or band name with no spaces <br> If found, the phone number will be displayed.</p>
    <form action="findPerformerD.php" method="get">
        <fieldset>
            <p align="left"> 
                <label> Performer/ band name: </label>
                <input type="text" name="performer" size="50"> <br>

                <input type="submit" name="submit" value="Submit performer name"> </p>
        </fieldset>
    </form>
</body>
</html>

This is what I have done, however when I try the html form, all it does is just give me a white page.

3

Answers


  1. Chosen as BEST ANSWER

    I have found the answer and managed to debug it finally :). if anyone wanted to see my code this is what I have came up with. Thank you for all the contributions.

    <!DOCTYPE html>
                    <html>
                    <body>
    
                    <?php
    
                    $filename = "performers.txt";
                    $myfile = fopen($filename, "r") or die("Unable to open file!");
    
                    $content = array();
                    while(!feof($myfile)) {
                        $content[] = fgets($myfile); 
                    }
    
                    fclose($myfile);
                    foreach($content as $line) {
                        $pieces = explode(' ', $line);
                        $content[trim($pieces[0])] = trim($pieces[1]);
                    }
    
    
                    //validating the input
                         function validPerformer($var){
                         $return = '<a href="phone_lookup.html">Return to form</a><br>';
                    //Checking if variable exists//
                            if(empty($var)){
                                echo $return; 
                                exit("Input does not exist. Please resubmit form."); //End function
                            }
                    //Checking if value is NOT numerical//
                            if(is_numeric($var)){
                                echo $return; 
                                exit("Invalid input. Variable must not be an integer.");
                            }
                    //Checking if any special characters are present//
                            if (preg_match('/[123456789'^£$%&*()}{@#~?><>,|=_+¬-]/', $var)){
                                echo $return; 
                                exit("Invalid characters. Please resubmit form.<br>.");
                           }
                           if (preg_match("/ /", $performer)) {
                        echo $return;
                        exit ("Invalid input. Only one word is allowed.");
                    }
                        $performer = $_GET['performer'];
                        $performerup = $performer[0]; 
                           if (!ctype_upper($performerup)) {
                               echo $return;
                               exit ("Invalid input. Please ensure that the performer's name starts with a capital letter.");
                            }
    
                           return $var;
                         }
                    $validatedp = validPerformer($_GET['performer']);
    
    
                    if (isset($validatedp))
                    {
                      if (isset($content[$validatedp]))
                      {
                        echo "Phone number is: ".$content[$validatedp];
                      }
                      else
                      {
                        exit ("No matching performer found<br>");
                      }
                    }
    
                     
                    ?>
                    </body>
                    <html>
    

  2. Firstly, your form submits via GET not POST, so nothing in $_POST will be populated.

    You can change

    <form action="findPerformerD.php" method="get">
    

    to

    <form action="findPerformerD.php" method="post">
    

    to resolve that.

    Secondly, you are looping through the $data array twice for no apparent reason. This isn’t helping you to find the matching data.

    In fact though you don’t even a loop at all to do the test:
    . Instead you can try to access the performer record directly – that’s what’s useful about using an associative array with the performer’s name as the index.

    In your PHP, replace the whole of the foreach ($data as $name => $phoneno) { ... } section with:

    if (isset($_POST['performer']))
    {
      if (isset($data[$_POST['performer']]))
      {
        echo "Phone number is: ".$data[$_POST['performer']];
      }
      else
      {
        echo "No matching performer found";
      }
    }
    

    Therefore if you were, for example, to input Lauren into the form, you’d expect it to output "Phone number is: 0382718319"

    Login or Signup to reply.
  3. PHP has a native function to help you open a file and parse formatted lines. fscanf() looks perfect for the task; this will eliminate that extra loop and more directly generate the desired lookup array.

    $filename = "performers.txt";
    $handle = fopen($filename , "r");
    while ([$name, $lookup[$name] = fscanf($handle, "%s %s"));
    fclose($handle);
    

    As a general rule, when you are submitting data to a script that is going to "write" to the server (affect the database or filesystem), use POST. When only "reading" from the server, use GET.

    In your case, GET seems appropriate to me.

    if (!isset($_GET['performer'])) {
        echo "Missing/Invalid performer submitted";
    } elseif (empty($lookup)) {
        echo "Failed to populate lookup";
    } elseif (!isset($lookup[$_GET['performer']])) {
        echo "Performer not found";
    } else {
        echo $lookup[$_GET['performer']];
    }
    

    Using a lookup and searching for keys will ALWAYS be faster than making value searches in PHP.

    You might only bother to read and parse your file if isset($_GET['performer']) is actually true.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search