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)
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:
JavaScript
x
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:
JavaScript
$emails = explode("n", str_replace("r", "", $_POST['email_address'])); //return an array
Second Solution:
JavaScript
$emails = explode(PHP_EOL, $_POST['email_address']);
Third Solution:
JavaScript
$emails = array_values(array_filter(explode(PHP_EOL, $_POST['email_address'])));