2

您好,我正在从数据库中的文本区域保存电子邮件地址。现在我希望将这些数据放入一个数组中,以便我可以向每个电子邮件地址发送一封邮件。

在每个换行符上都有一个电子邮件地址,如下所示:

<textarea>
my@email.com 
my2@email.com 
my3@email.com
</textarea>

此数据以 LONGTEXT 格式保存在数据库中。我将这些数据作为字符串从数据库中取出。但我希望将数据放入一个数组中。所以每封电子邮件都有一个唯一的索引。请注意,数据库中没有保存像 '\n' 和 <br> 这样的特殊字符。

提前致谢!

4

6 回答 6

3

Your question seems to indicate that you're saving the email addresses in the textarea as whole rather than first splitting them up and saving each address separately. You will want to take the latter approach. Why split/validate everytime you read out of the database?

First, split the incoming emails with:

$email_addresses = preg_split('/\r\n|\n|\r/', $_POST['email_addresses']);

The regex allows you to take into account the different end of line characters the different platforms out there use.

Then you can loop over the addresses and validate each with:

filter_var($email_address, FILTER_VALIDATE_EMAIL)

Then save each address in its own row in the database.

于 2012-05-09T15:34:01.000 回答
2

假设您的数据库字段被调用email_addresses并且新行是\n

$email_addresses = explode("\n", $row['email_addresses']);
于 2012-05-09T15:13:09.870 回答
1

是的,正如上面提到的两个不错的答案,您可以使用

$email_addresses = explode("\n", $row['email_addresses'];

完成你所需要的。但是,他们确实忘记提及您正在做的事情是个坏主意。您所做的事情会给 SQL 注入带来巨大的安全风险。看我可以放置类似的东西

test@aol.com'; DELETE * FROM employees WHERE 1 OR email = '

如果您有这样的语句设置,请在该文本框中删除您的表格

Select * FROM employees where email = '$email_addresses[0]'

一个简单的解决方案是在您的每个电子邮件地址上使用“mysql_real_escape_string($string)”,或者使用正则表达式,例如

^[A-Za-z0-9._+-]+@[A-Za-z0-9.-]{2,}+\.[A-Za-z]{2,4}$

尝试使用这些资源让您走上正确的轨道,以防止您的整个数据库受到攻击:

如何防止 PHP 中的 SQL 注入?

http://php.net/manual/en/security.database.sql-injection.php

http://bit.ly/ICJhZJ

于 2012-05-09T15:41:20.667 回答
0

你试过什么?

尝试这个 :

<?php
$array = explode("\n", $your_long_text);
于 2012-05-09T15:14:22.270 回答
0

为了安全起见,您应该这样做:

<?php
    $array = explode('|', str_replace(array("\n","\r"),'|',$your_long_text));
    foreach ($array as $k => $v)
         if (empty($v)) unset($array[$k]);
?>

这涵盖了所有类型的换行符,并删除了可能出现的任何空条目。

于 2012-05-09T15:27:27.670 回答
0

我重新解决了我的问题并遵循了 webbiedave 的建议。我首先拆分电子邮件地址并检查它们是否有效。之后,我将每个条目保存为数据库中的一行。

// Delete previous Emails
        DB::_execute("DELETE FROM `%s` WHERE education_id = ?", array(self::_getEducationEmailAddressesTable()), array($action['id']));

        // Only save new emails when email is not empty
        if( ! empty($data['emails'])) {
            // save Emails 
            $email_addresses = preg_split('/\r\n|\n|\r/', $data['emails']);

            foreach($email_addresses as $email) {
                if( ! Utils::_isEmailAddress($email)) {
                    return new Error("GiveValidEmailAddress");
                } else {
                    DB::_execute("INSERT INTO `%s` (education_id, email_address) VALUES (?, ?)", array(self::_getEducationEmailAddressesTable()), array($action['id'], $email));    
                }
            }
        }
于 2012-05-10T07:13:11.777 回答