将数据从一个表移动到另一个表时出错

时间:2012-05-29 15:04:44

标签: php mysql copy move

$feedback_list = array( 
    array('date1', '87586cb8b79861edcc4e6a12104b87529c53050375904ff180'), 
    array('date2', 'abc1d08c3e42cffa7eaaa84eb4fe04b44c34be497ce7e8ea26') 
);

foreach($feedback_list as $feedback) {
    $result = mysql_query("INSERT INTO 'inactive_users' (token, username) 
       SELECT (token, username) FROM active_users WHERE token = '$feedback[1]'");
    if (!mysql_query($result,$con)) { die('Error: ' . mysql_error()); }
}

..回显正确的值,该值也存在于active_users表中,但该值不会复制到第二个表中。错误是:

  

错误:查询为空

3 个答案:

答案 0 :(得分:1)

应该是这样的:

foreach($feedback_list as $feedback) {
    $result = mysql_query("INSERT INTO inactive_users (token, username) SELECT token, username FROM active_users WHERE token = '{$feedback[1]}'");
}

答案 1 :(得分:1)

你永远不应该把一个mysql_query放在循环中。

INSERT语句可以聚合成一个大字符串。

与我在开头所说的相反,你应该使用循环来表示你的select语句,然后取结果并连接你的插入查询;在循环之后执行它

一个例子

$feedback_list = array( 
array('date1', '87586cb8b79861edcc4e6a12104b87529c53050375904ff180'), 
array('date2', 'abc1d08c3e42cffa7eaaa84eb4fe04b44c34be497ce7e8ea26') 
);
$insert = null;
$select = "SELECT (token, username) FROM active_users WHERE token = '%s'";
foreach($feedback_list as $feedback) {
    $sql = print_f($select, $feedback[1]);
    $result = mysql_query($sql) or die("SQL:$sql<br />\n". mysql_error());
    $values = mysql_fetch_row($result);
    //$values['token'] => token
    //$values['username'] => username

    $insert .= "INSERT INTO 'inactive_users' (token, username) VALUES ('{$values['token']'}','{$values['username']}')\n";
}
 $theInsert = mysql_query($insert);

答案 2 :(得分:1)

您正在运行mysql_query两次。尝试

foreach($feedback_list as $feedback) {
    $result = "INSERT INTO `inactive_users` (token, username) 
       SELECT token, username FROM active_users WHERE token = '{$feedback[1]}'";
    if (!mysql_query($result,$con)) { die('Error: ' . mysql_error()); }
}