2011-07-26 49 views
0

恐怕这听起来多余。我已经尽了我的努力,并至少取代了我迄今发现的三个想法,但没有任何成效。将数组从一个表插入另一个表

目标是合并来自两个表格的唯一字段,但是现在我甚至无法从一个表格获取完全相同的字段,并将其创建为相同的表格。这里是迄今为止的代码,与我的意见:

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

在此先感谢您。我非常感谢你的帮助。

+0

改变您的查询行'的mysql_query( $ pop)或死(mysql_error());',重新运行,并告诉我们是否有任何错误。 –

+0

@Mark他肯定会得到一个MySQL语法错误。 – cwallenpoole

+0

嗯,我会<在这里插入你的结局>!错误是db.address_new不存在。不过,我可以看到它使用mysqlcc。 – CoffeeBean

回答

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"; 
+0

似乎我现在很难找到表格。当我解决问题时会应用这个。谢谢! – CoffeeBean

+0

谢谢你,cwallenpoole。这个问题源于程序的早期设置数据库句柄,然后设置一个pconnect ...愚蠢的错误。在我将$ dbh句柄作为mysql_query的参数添加后,一切正常(你也是)。 – CoffeeBean

相关问题