skip to Main Content

How to save long text from textarea-input line per line
i have a form with a text area, i wanna save a long text line per line in mysql
i have no idea

$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        // process the line read.
        }

    fclose($handle);
}

2

Answers


  1. You need to learn how mysql interacts with the DB. You will likely need to use VARCHAR datatype depending on how big you text area is. So if the field from the from is up to 250 characters then the text area column’s datatype would be VARCHAR(250).

    You would do a POST request to a file with something like this:

    $post = $_POST;
    //set other fields here, I recommend sanitizing your inputs.
    ...
    $textarea = $_POST['text_area'];
    $servername = "HOST";   
    $username = "username"; 
    $password = "password";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password);
    
    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }
    $sql = "INSERT INTO MyGuests (...other columns you have, textarea)
           VALUES (..., $textarea)";
    
    if ($conn->query($sql) === TRUE) {
       echo "New record created successfully";
    } else {
       echo "Error: " . $sql . "<br>" . $conn->error;
    }
    

    Two links I highly suggested looking at:
    How to filter inputs via php(used before sql execution)
    PHP MySQL Insert Data

    Login or Signup to reply.
  2. It would have been easier if I had a look at your form data. I’ll assume my own form data to try and answer your question.
    form.php

                <form action="processing.php" method="POST">
                      <textarea required name="records" class="form-control" rows="8" cols="4" placeholder="Enter records separated by new line"></textarea>
                  <button type="submit" name="addRecords" class="btn btn-warning">Add Records</button>
                </form>
    

    Then processing.php

    if (isset($_POST['addRecords'])) {
        $record = $_POST['records'];
        //explode records based on new line n
        $records = explode("n", $record);
    
        foreach ($records as $new) {
          $data = $new;
          //Here you'll write your sql code to insert records in the database
          
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search