SQL / PHP将列从一个表插入另一个表

时间:2013-10-29 10:48:11

标签: php insert

您好我处理简单的新闻稿脚本,我在那里有两个小组,每个小组有两个不同的表。

我想将订阅者从一个群组转移到另一个群组,我将此查询与其有效:

$sql = "INSERT INTO newsletter_subscribers2 SELECT * FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";

然而,在移动了一些以前的订阅者之后,我收到了重复输入密钥的错误,因为我使用ID移动查询,所以我只需要移动,姓名,姓氏和电子邮件。

$sql = "INSERT INTO newsletter_subscribers2 VALUES (firstname, lastname, email) SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname, newsletter_subscribers.email FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";

然而,这部分代码似乎没有工作,因为我遇到语法错误,任何人都可以帮助我,我会很高兴。

感谢您的回复

3 个答案:

答案 0 :(得分:0)

删除VALUES

$sql = "INSERT INTO newsletter_subscribers2 (firstname, lastname, email) 
        SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname, 
               newsletter_subscribers.email 
        FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";

编辑:并始终使用mysql_real_escape_string来阻止SQL注入:

$sql = "... WHERE id='".mysql_real_escape_string($_GET['nid'])."'";

答案 1 :(得分:0)

您必须删除values

  $sql = "INSERT INTO newsletter_subscribers2(firstname, lastname, email) 
   SELECT newsletter_subscribers.firstname, newsletter_subscribers.lastname, 
   newsletter_subscribers.email 
   FROM newsletter_subscribers WHERE id='".$_GET['nid']."'";

答案 2 :(得分:0)

试试这个:

insert into newsletter_subscribers2 (col1, col2, col3, etc) select col1, col2, etc from newsletter_subscribers2  where 1 = 1