将数组从一个表插入另一个表

时间:2011-07-26 02:07:15

标签: php mysql

我担心这听起来多余。我已经完成了我的努力,至少取代了迄今为止我发现的三个想法,但没有任何作用。

目标是合并两个表中的唯一字段,但是现在我甚至无法从一个表到另一个表创建相同的字段作为相同的表。这是迄今为止的代码,我的评论是:

$result = mysql_query("SELECT * from $db.$tbl LIMIT 50");

if($result) {
while($maindata = mysql_fetch_assoc($result)) {

$newdata = implode ("," , $maindata);

$newdata = mysql_escape_string($newdata);

$pop = "INSERT INTO $db.address_new (id,entitynum,address,city,state,zip,country,remarks)
SELECT FROM $db.address";        

//This is the original code replaced by the above
//$pop = "INSERT INTO $db.address_new (id,entitynum,address,city,state,zip,country,remarks)
//  VALUES ($newdata)"; 

mysql_query($pop);

//print_r($pop);
   //Seems to give the correct output in the browser, but the table address_new remains empty. `

提前谢谢你。我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:2)

直接从另一个表中插入(注意:如果ID为auto_increment,您可能想也可能不想以这种方式插入):

INSERT INTO db.address_new (id,entitynum,address,city,state,zip,country,remarks)
   SELECT (id,entitynum,address,city,state,zip,country,remarks) 
      FROM db.address LIMIT 50

(不要把它放在循环中)

如果您正在寻找独特的价值观,您可以通过以下几种方式实现这一目标。就个人而言,我会在一个(或一组)值上有一个唯一的键,然后只做INSERT IGNORE

INSERT IGNORE INTO db.address_new 
  (id,entitynum,address,city,state,zip,country,remarks)
   SELECT (id,entitynum,address,city,state,zip,country,remarks) 
      FROM db.address LIMIT 50

作为旁注:

// use mysql_real_escape_string 
mysql_escape_string($newdata); 

// since you're passing this through PHP, you need to make sure to quote 
// all of your values. This probably means you'll need to loop and replace this
// $newdata = implode ("," , $maindata);
// with something like:

$newdata = array();
foreach( $maindata as $column )
{
    $newdata[] = "'" . mysql_real_escape_string( $column ) . "'";
}
$newdata = implode(',', $newdata);


// you're missing the columns in your select clause. 
$pop = "INSERT INTO $db.address_new ".
       "(id,entitynum,address,city,state,zip,country,remarks) ".
       // You need to select *something*
       "SELECT FROM $db.address"; 
相关问题