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


Insert array from one table to another

我担心这听起来是多余的。我已经做了我的努力,并取代了至少三个想法,我发现到目前为止,没有任何工作。

目标是合并两个表中的唯一字段,但是现在我甚至不能从一个表中将相同的字段获取到另一个创建为相同表的表中。下面是到目前为止的代码,加上我的注释:

$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. `

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

直接从另一个表插入(注意:如果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";