There is an input form. It is necessary to fill the array with data from the form and display. But I can't accumulate records. Each entry erases the previous one. How to make the records added to the array?

<form action="/notes.php" method="post"> <label for="text">Новая запись:</label> <input type="text" name="text" id="text"><br> <button type="submit">Добавить новую запись</button> </form> <?php $arr = []; $newNote = $_POST['text']; $arr[] = $newNote; foreach ($arr as $value){ echo $value; } ?> 

    2 answers 2

    How to make the records added to the array?

    To use the session for input / output notes.php , before the completion you need to save to one of the options below:

     <?php session_start(); // Добавит запись потом можно будет вывести $_SESSION['notes'][] = filter_var ($_POST['text'], FILTER_SANITIZE_STRING); 

    Use files for I / O records (not the best)

     $note = filter_var ($_POST['text'], FILTER_SANITIZE_STRING); $yor_file = file_put_contents('notes.txt', $note.PHP_EOL , FILE_APPEND | LOCK_EX); 

    Use database for I / O records (recommended)

     $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = "INSERT INTO notes (text) VALUES (:text)"; $stmt = $conn->prepare($sql); $stmt->bindParam(':text', $_POST['text']); $stmt->execute(); 

    It will be more logical to print it out later, on the page that sent these records.

    Rather, in conjunction with the session, which until completion will save everything to the database, it will be the best solution.


    • $ _SESSION - An associative array containing session variables that are available for the current script.
    • file_put_contents - If notes.txt does not exist, a file will be created. Add a new FILE_APPEND entry to the file.
    • PDO class - Represents a connection between PHP and a database server.

      You have a dubious idea, but so be it:

       <form action="/notes.php" method="post"> <label for="text">Новая запись:</label> <input type="text[]" name="text[]" id="text"><br> <?php if (isset($_POST['text'])) foreach ($_POST['text'] as $value){ echo '<input type="hidden" name="text[]" value="'.$value.'">'; } ?> <button type="submit">Добавить новую запись</button> </form> <?php if (isset($_POST['text'])) foreach ($_POST['text'] as $value){ echo $value.'<BR>'; } ?> 
      • I get the error "Invalid argument supplied for foreach ()" - Alexander