1

I have a form which takes a student name, subject and age. When submitted, it saves the data as an array in txt file. Next time, when I put new data and submit it, it creates a new array in that txt file instead of appending it to the previous array.

<?php
if(!empty($_GET)){
    $student = [];
    $student['name'] = $_GET['name'];
    $student['subject'] = $_GET['subject'];
    $student['age'] = $_GET['age'];
    $studentArray = [];
    array_push($studentArray, $student);
    $str = print_r($studentArray, true);
    file_put_contents('student.txt', $str, FILE_APPEND);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="" method="GET">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">

        <label for="name">Subject:</label>
        <input type="text" name="subject" id="subject">

        <label for="name">Age:</label>
        <input type="number" name="age" id="age">

        <input type="submit" name="submitButton">
    </form>
</body>
</html>

output looks like this:

enter image description here

however I want to save it like below:

enter image description here

How could I do that?

1
  • 4
    Read in the file (if possible, you should save as JSON instead) into an array, append data, then overwrite the file with the entire array. That output format is for debugging though, use json_encode and json_decode. Commented Oct 24, 2020 at 11:14

3 Answers 3

2

If you really have to see your nice array in text use this:

    if(!empty($_GET)){
        $student = array();
        $int = 0;
        $txtfile = "student.txt";
        if (file_exists($txtfile)) {
            $fgc = file_get_contents($txtfile);
            $expl = explode("[".$int."] => Array", $fgc);
            while (count($expl) > 1) {
                $expl2 = (count($expl) > 1) ?  explode("[".($int+1)."] => Array", $expl[1])[0] : $expl[1];
                $m = preg_match_all("@\\[([\d\w]+)\\] => ([^\n]*)@imus", $expl2, $matches);
                if ($m == 0) { break; }
                foreach ($matches[1] as $key => $val) {
                    $student[$int][$val] = $matches[2][$key];
                }
                $int++;
                $expl = explode("[".$int."] => Array", $fgc);
            }
        }
        $student[$int]['name'] = $_GET['name'];
        $student[$int]['subject'] = $_GET['subject'];
        $student[$int]['age'] = $_GET['age'];
        $str = print_r($student, true);
        file_put_contents('student.txt', $str);

        print_r($student);
    }

But please use a serialized version like this:

    if(!empty($_GET)){
        $student = array();
        $int = 0;
        $txtfile = "student.txt";
        if (file_exists($txtfile)) {
            $fgc = file_get_contents($txtfile);
            $student = unserialize($fgc);
            $int = count($student);
        }
        $student[$int]['name'] = $_GET['name'];
        $student[$int]['subject'] = $_GET['subject'];
        $student[$int]['age'] = $_GET['age'];
        file_put_contents('student.txt', serialize($student));

        print_r($student);
    }

print_r for debug only.

Have fun ;)

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use JSON in order to update your array constantly. the important point is you have to load your students in a variable and then push the new student to that variable so, in the end, you can save your students variable which contains all students in one array like you want.

Requirements to make this code works:

  1. Create a file named student.json and put [] inside the file

Also, I highly suggest go and learn about JSON in PHP so you can have a better understanding of how this code is working now

if(!empty($_GET)){
    $student = [];
    $student['name'] = $_GET['name'];
    $student['subject'] = $_GET['subject'];
    $student['age'] = $_GET['age'];
    $studentArray = json_decode( file_get_contents('student.json'), true);
    array_push($studentArray, $student);
    $str = print_r($studentArray, true);
    file_put_contents('student.json', json_encode($studentArray));
}

3 Comments

Thanks for your answer. However, using your code, I still can't save them as an array in JSON. student.json file show null.
Hey, you right it probably won't work at all because I have one typing mistake at line 6 (Typed file_get_contentes beside file_get_contents). the new code should work now.
Hey, actually I noticed the tying mistake and corrected it. And it didn’t work.
0

The Simplest way to store form data in an array is following.

 <?php 

  // Stores form data
  $form_data = array();

  // On form submission via post method, form data will stored to the array
  if($_POST){
    $form_data = $_POST['form_data'];

    // Print data
    echo("<pre>");
    print_r($form_data);
    echo("</pre>");
}
 ?>

   <--! Form -->
   <form method="POST" action="form_data.php" >
       
      <!-- Insert -->
      <input type="text" name="form_data[fullname]" />
      <input type="text" name="form_data[email]" />
      <input type="text" name="form_data[address]" />

      <!-- Submit -->
      <button  type="submit">Submit</button>

    </form>

After inserting data in the input fields and submitting the form. The data will be sent to the page that is mentioned in action tag. In this example, same page is mentioned. So, data will be printed on the same form page.

Result Will Look Like This enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.