code
code

Reputation: 1081

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


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;
            }
            
        } 
    }
}

Upvotes: 0

Views: 40

Answers (1)

Burhan Kashour
Burhan Kashour

Reputation: 677

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'])));

Upvotes: 1

Related Questions