skip to Main Content

I am doing a school practice sac where I have to create a program where the scenario is that:

Penelope is moving house and knows that it will be quite an expensive time. She needs a program that will allow her to add up how much it will cost to furnish each room. She has been creating a text file with the furniture items and prices as she visits online furniture stores.

The solution needs to:

  • Enter up to five chosen furniture items and quantities
  • See the items she has selected, the quantity required, the price of each item and the total price of all items combined.

this is what the html form looks like ( i am not allowed to edit the html form)
(https://phpout.com/wp-content/uploads/2024/03/4hpeW.png)

So basically I need to create an array using the text file which has the following content:

Dining Table, 595.00
Dining Chair, 145.00
Coffee Table, 259.99
3 Seater Couch, 1200.00
2 Seater Couch, 990.00
Desk, 375.50
Desk Chair, 123.60
Bookshelf- large, 495.99
Bookshelf- small, 298.90
Single Bed, 675.60
Queen Bed, 986.30


I have successfuly done so by making it into an array where the furniture and price are together but are split into different sections as so:

Array ( [0] => Dining Table, 595.00 [1] => Dining Chair, 145.00 [2] => Coffee Table, 259.99 [3] => 3 Seater Couch, 1200.00 [4] => 2 Seater Couch, 990.00 [5] => Desk, 375.50 [6] => Desk Chair, 123.60 [7] => Bookshelf- large, 495.99 [8] => Bookshelf- small, 298.90 [9] => Single Bed, 675.60 [10] => Queen Bed, 986.30 )


However my issue is creating an array from the input. I am aware on how to request and get the input, and I know hwo to validate the input to ensure that the input is correct (no strings in the quantity form, that the variable exists in the array so on). But my concern is to how to assign it so that the first furniture input
(https://phpout.com/wp-content/uploads/2024/03/dvKCI.png)
is able to be assigned to the correct part of the and array, and to be able to calculate the quantity with the RIGHT furniture, therefore I woul get the total price. I hope my explanation makes sense.


If you wish to see my full code:

<!-- //Furniture Calculator PHP | Version 1.1 | Sara WU//  -->
                <!DOCTYPE html>
                <html>
                <body>

                <?php
                $filename = "Furniture.txt";
                $arrFurn = array();
                $fp = fopen($filename, "r");

                if(filesize($filename) > 0){
                    $content = fread($fp, filesize($filename));
                    $arrFurn = explode("n", $content);
                    fclose($fp);
                }

                //Function for checking the validation of the string//
                    function validString($var){
                    $return = 'Return to <a href="FurnitureCalculator.html">Return to Form</a><br>';

                //Checking if variable exists in array//
                      if (!in_array($var, $arrFurn)) {
                            echo $return;
                            exit("Your input does not exist in the text file."); //End function
                        }

                //Checking if variable exists//
                      if(empty($var)){
                            echo $return; 
                            exit("Input does not exist. Please resubmit form."); //End function
                        }
                //Checking if variable is numerical//
                      if (is_numeric($var)){
                            echo $return; 
                            exit("Invalid input. Value is not a string."); //End function
                       }
                //Checking if any special characters are present//
                      if (preg_match('/[1234567890'^£$!%&*()}{@#~?><>|=_+¬-]/', $var)){
                            echo $return; 
                            exit("Invalid characters. Please resubmit form.<br>.");
                       }
                            return $var;

                    }
                    // echo validString('poop!'); PASSED


                //Validation for checkin integers//
                     function validInt($var, $min = 1, $max = 99 ){
                     $return = 'Return to <a href="FurnitureCalculator.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 be na");
                        }
                //Checking if any special characters are present//
                      if (preg_match('/['^£$%&*(!)}{@#~?><>,|=_+¬-]/', $var)){
                            echo $return; 
                            exit("Invalid characters. Please resubmit form.<br>.");
                       }
                //Checking if variable fits within required length//
                       if($var < $min || $var > $max){
                            echo $return; 
                            exit("Value exceeds characters limit.");
                        }
                       return $var;
                     }

                     // echo validInt(-7,1,99); PASSED


                //Retrieves variables from html form//
                   
                     $quan1 = validInt($_GET['quan1']);
                     $quan2 = validInt($_GET['quan2']);
                     $quan3 = validInt($_GET['quan3']);
                     $quan4 = validInt($_GET['quan4']);
                     $quan5 = validInt($_GET['quan5']);
                     $furn1 = validString($_GET['furn1']);
                     $furn2 = validString($_GET['furn2']);
                     $furn3 = validString($_GET['furn3']);
                     $furn4 = validString($_GET['furn4']);
                     $furn5 = validString($_GET['furn5']);
                //prints out the furniture the user have have inputted// 
                     print "This is the following furniture you have ordered: <br>";
                     print('1.'. $furn1 . '<br>'.'2.'. $furn2 .'<br>'.'3.'. $furn3 .'<br>'.'4.'. $furn4 .'<br>'.'5.'. $furn5 .'<br>');

                //prints out the quantity that the user have ordered//
                     print "This is the following quantity you have ordered: <br>";
                     print($furn1 .":". $quan1 .'<br>' . $furn2 .":". $quan2 .'<br>' . $furn3 .":". $quan3 .'<br>' . $furn4 .":". $quan4 .'<br>'. $furn5 .":". $quan5 .'<br>');


                //calculating total price


                //prints out the total price//
                     print("The total price of your order is ;")





                ?>

</body>
</html>

2

Answers


  1. I’ve refactored quite a bit of your code, hopefully to make things easy to understand and to cut down on some unnecessary code.

    Below I have explained what I have changed and what we are doing. At the end of my post is the full new code.

    Furniture Costs

    Capture the furniture and it’s costs in an array ($arrFurn) where the furniture item is the key and the cost is the value. Later, when they request an item, we can check if the array key exists, then we know whether the requested item is in the txt file.

    if (filesize($filename) > 0) {
        $content = fread($fp, filesize($filename));
        $tempArrFurn = explode("n", $content);
    
        // Store the data where the furniture name is the key and cost is the value
        // This will make it easier to check if the furniture item they request is valid
        foreach($tempArrFurn as $furn) {
            $arrFurnitureCosts = explode(",", $furn);
            $furnitureName = trim($arrFurnitureCosts[0]);
            $furnitureCost = trim($arrFurnitureCosts[1]);
            $arrFurn[$furnitureName] = $furnitureCost;
        }
        fclose($fp);
    }
    

    validString function

    1. Inside the function, I’ve declared $arrFurn as a global, so we can read the data inside it.

    2. I’ve also changed the if(!in_array()) check to an if(!isset()) check as I changed the way you are soring the furniture item and the cost.

      function validString($var) {
      
      // Get access to the array $arrFurn
      global $arrFurn;
      
      $return = 'Return to <a href="FurnitureCalculator.html">Return to Form</a><br>';
      
      // Trim the input to remove any leading or trailing spaces
      $var = trim($var);
      
      //Checking if variable exists in array//
      if (!isset($arrFurn[$var])) {
          echo $return;
          exit("Your input does not exist in the text file."); //End function
      }
      
      //Checking if variable exists//
      if (empty($var)) {
          echo $return;
          exit("Input does not exist. Please resubmit form."); //End function
      }
      //Checking if variable is numerical//
      if (is_numeric($var)) {
          echo $return;
          exit("Invalid input. Value is not a string."); //End function
      }
      //Checking if any special characters are present//
      if (preg_match('/[1234567890'^£$!%&*()}{@#~?><>|=_+¬-]/', $var)) {
          echo $return;
          exit("Invalid characters. Please resubmit form.<br>.");
      }
      return $var;
      
      }
      

    Process the input form data

    This builds an array of the items requested, quantity requested and the total cost of that item. E.G. If they request 3 x Dining Chairs, this calculates 3 * DiningChairCost

    //Retrieves variables from html form & calculate the total cost for each furniture item
    $noOfChoices = 5;
    $requestedItems = array();
    for ($i = 1; $i <= $noOfChoices; $i++) {
        $quantityRequested = validInt($_GET['quan' . $i]);
        $furnitureRequested = validString($_GET['furn' . $i]);
    
        // Build an array of the furniture items requested, quantity requested & calculate the total cost for this furniture
        $requestedItems[] = [
            'furniture' => $furnitureRequested,
            'quantity' => $quantityRequested,
            'cost' => $arrFurn[$furnitureName] * $quantityRequested
        ];
    }
    

    Print out the order and the costs

    The below snippet will print out a list of the requested furniture, quantity, price and then at the very end, the total price for all the items requested

    // Prints out the furniture, quantity & cost for each requested item & calculates the overall total
    print "This is a list of what furniture you have requested, the quantity you have ordered and the total for each furniture item: <br>";
    $totalOrderPrice = 0;
    foreach ($requestedItems as $item) {
        $furniture = $item['furniture'];
        $qty = $item['quantity'];
        $cost = number_format($item['cost'], 2, ".", ",");
    
        // E.G.       Item: 3x Dining Chair = 435.00
        echo "Item: " . $qty . "x " . $furniture . " = " . $cost . "<br>";
    
        // Calculate the total order price
        $totalOrderPrice += $item['cost'];
    }
    
    
    //prints out the total price//
    echo "The total price of your order is ;" . number_format($totalOrderPrice, 2, ".", ",");
    

    Full Code

    Below is the new full page code

    <!-- //Furniture Calculator PHP | Version 1.1 | Sara WU//  -->
    <!DOCTYPE html>
    <html>
    <body>
    
    <?php
    $filename = "Furniture.txt";
    $arrFurn = array();
    $fp = fopen($filename, "r");
    
    if (filesize($filename) > 0) {
        $content = fread($fp, filesize($filename));
        $tempArrFurn = explode("n", $content);
    
        // Store the data where the furniture name is the key and cost is the value
        // This will make it easier to check if the furniture item they request is valid
        foreach ($tempArrFurn as $furn) {
            $arrFurnitureCosts = explode(",", $furn);
            $furnitureName = trim($arrFurnitureCosts[0]);
            $furnitureCost = trim($arrFurnitureCosts[1]);
            $arrFurn[$furnitureName] = $furnitureCost;
        }
        fclose($fp);
    }
    
    //Function for checking the validation of the string//
    function validString($var)
    {
    
        // Get access to the array $arrFurn
        global $arrFurn;
    
        $return = 'Return to <a href="FurnitureCalculator.html">Return to Form</a><br>';
    
        // Trim the input to remove any leading or trailing spaces
        $var = trim($var);
    
        //Checking if variable exists in array//
        if (!isset($arrFurn[$var])) {
            echo $return;
            exit("Your input does not exist in the text file."); //End function
        }
    
        //Checking if variable exists//
        if (empty($var)) {
            echo $return;
            exit("Input does not exist. Please resubmit form."); //End function
        }
        //Checking if variable is numerical//
        if (is_numeric($var)) {
            echo $return;
            exit("Invalid input. Value is not a string."); //End function
        }
        //Checking if any special characters are present//
        if (preg_match('/[1234567890'^£$!%&*()}{@#~?><>|=_+¬-]/', $var)) {
            echo $return;
            exit("Invalid characters. Please resubmit form.<br>.");
        }
        return $var;
    
    }
    
    // echo validString('poop!'); PASSED
    
    
    //Validation for checkin integers//
    function validInt($var, $min = 1, $max = 99)
    {
        $return = 'Return to <a href="FurnitureCalculator.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 be na");
        }
        //Checking if any special characters are present//
        if (preg_match('/['^£$%&*(!)}{@#~?><>,|=_+¬-]/', $var)) {
            echo $return;
            exit("Invalid characters. Please resubmit form.<br>.");
        }
        //Checking if variable fits within required length//
        if ($var < $min || $var > $max) {
            echo $return;
            exit("Value exceeds characters limit.");
        }
        return $var;
    }
    
    // echo validInt(-7,1,99); PASSED
    
    
    //Retrieves variables from html form & calculate the total cost for each furniture item
    $noOfChoices = 5;
    $requestedItems = array();
    for ($i = 1; $i <= $noOfChoices; $i++) {
        $quantityRequested = validInt($_GET['quan' . $i]);
        $furnitureRequested = validString($_GET['furn' . $i]);
    
        // Build an array of the furniture items requested, quantity requested & calculate the total cost for this furniture
        $requestedItems[] = [
            'furniture' => $furnitureRequested,
            'quantity' => $quantityRequested,
            'cost' => $arrFurn[$furnitureName] * $quantityRequested
        ];
    }
    
    // Prints out the furniture, quantity & cost for each requested item & calculates the overall total
    print "This is a list of what furniture you have requested, the quantity you have ordered and the total for each furniture item: <br>";
    $totalOrderPrice = 0;
    foreach ($requestedItems as $item) {
        $furniture = $item['furniture'];
        $qty = $item['quantity'];
        $cost = number_format($item['cost'], 2, ".", ",");
    
        // E.G.       Item: 3x Dining Chair = 435.00
        echo "Item: " . $qty . "x " . $furniture . " = " . $cost . "<br>";
    
        // Calculate the total order price
        $totalOrderPrice += $item['cost'];
    }
    
    
    //prints out the total price//
    echo "The total price of your order is ;" . number_format($totalOrderPrice, 2, ".", ",");
    
    
    ?>
    
    </body>
    </html>
    
    Login or Signup to reply.
  2. Since the advice that I really want you to use is posted on a subsequent deleted question of yours, I want to preserve my advice on your earliest question which pertains to the same task. The only thing that changed was furniture to performers.

    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 (empty($_GET['performer'])) {
        echo "No performer submitted";
    } elseif (!ctype_alpha($_GET['performer'])))) {
        echo "Performer value must only contain letters";
    } 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.

    Using these scripts, you will be able to reliably validate and return corresponding details to the end user.

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