Skip to content
Advertisement

It’s only inserting the last value from a textarea

I’m placing a bunch of emails into a html textarea form. I need to insert the email addresses into my database so I’m using INSERT INTO but for some reason it’s only inserting the last value (email). I’m separating the emails with a line break when placing them into the textarea. (see image below)

screenshot of textarea containing email addresses

Also, is it ok to put a sql query inside a loop?

Example Emails

  • toku***@att.net
  • fros***@gmail.com
  • jpfl***@sbcglobal.net
  • besc***@msn.com
  • pgot***@icloud.com
  • seth***@outlook.com 🔴 This is the only email that gets recorded to the database!

Code:

if(isset($_POST["add"]))
{
    if(empty($_POST["email_address"]))
    {
        $error = '<label class="text-danger">Email Address List is required</label>';
    }
    else
    {
        
        $emails = explode(",", $_POST['email_address']);

        foreach($emails as $value)
        {
            $sql = "INSERT INTO contacts (username, email)
            VALUES ('beta', '$value')";

            if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
            } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
            }
            
        } 
    }
}

Advertisement

Answer

if you use textarea then you can do the following:

First Solution:

$emails = explode("n", str_replace("r", "", $_POST['email_address'])); //return an array

Second Solution:

$emails = explode(PHP_EOL, $_POST['email_address']);

Third Solution:

$emails = array_values(array_filter(explode(PHP_EOL, $_POST['email_address'])));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement