维护用户列表 - MySQL / PHP

时间:2012-01-11 01:11:33

标签: php mysql list

我有一张表memberships

我向用户提供了一个文本框,其中包含memberships中当前电子邮件的列表。他们可以编辑列表。一旦他们发回列表,我想更新成员资格,使包含用户提供的列表中的电子邮件。

我能想到的最好的方法就是删除所有电子邮件,然后重新插入整个列表。有更好的方法吗?

我现在在做什么:

  $mysql->query('DELETE FROM memberships');

  $userEmails = explode('\n', $_POST['users']);
  foreach ($userEmails as $email)
    $mysql->query('INSERT INTO memberships (email) VALUES (?)', $email);

2 个答案:

答案 0 :(得分:2)

这样的事情可能是你正在寻找的(未经测试)。在使用查询以防止sql注入之前,不要忘记转义输入。

$userEmails = explode("\n", mysql_real_escape_string($_POST['users']));
$mysql->query("DELETE FROM `memberships` WHERE `email` NOT IN ('".implode("','", array_values($userEmails))."');");
$mysql->query("REPLACE INTO `memberships` (`email`) VALUES ('".implode("'),('", array_values($userEmails)).");");

答案 1 :(得分:2)

@BloodyWorld刚刚提交了一个更好的基于MySQL的解决方案,因为我输入了这个,但我还是提交了这个!

你可以尝试这个解决方案:

// Pull the current list of emails from the database
$current_emails = $mysql->query('SELECT email FROM memberships');
$user_emails = explode('\n', $_POST['users']);

// This array will contain only the emails to add
$new_emails = array_diff($user_emails, $current_emails);  

// This array will contain only the emails to delete
$deleted_emails = array_diff($current_emails, $user_emails);

// Add the new ones
foreach ($new_emails as $email)
  $mysql->query('INSERT INTO memberships (email) VALUES (?)', $email);

// Delete the old ones
$mysql->query("DELETE FROM memberships WHERE email NOT IN('".implode("','", $deleted_emails)."')");

它涉及更多代码,但它消除了所有成员在有机会循环并解析提交的文本之前从数据库中删除的可能性。您最终还会得到一系列“新”和“旧”成员,这些成员在此可能会有其他用途。