我必须从数据库中的表中选择数据并将它们插入到不同数据库中的另一个表中。以下代码返回$select_query
确定,但$insert_query
不正常。您能否更正代码并让我知道您的回复?
$host1 = "localhost";
$user1 = "jackpot";
$pass1 = "jackpot";
$db1 = "pinkapple";
$host2 = "localhost";
$user2 = "jackpot";
$pass2 = "jackpot";
$db2 = "blueberry";
$mysql_connection1 = mysql_connect($host1, $user1, $pass1);
mysql_select_db($db1, $mysql_connection1) or die(mysql_error());
$select_query = mysql_query("SELECT field1, field2, field3 FROM tree WHERE date_entered > '2014-01-01 16:22:00'", $mysql_connection1);
$number = mysql_num_rows($select_query);
if ($select_query) {
echo "Select Query is OK <br>";
echo $number ."<br>";
} else {
echo "Select Query is not OK <br>";
}
$mysql_connection2 = mysql_connect($host2, $user2, $pass2, true);
mysql_select_db($db2, $mysql_connection2) or die(mysql_error());
while ($row = mysql_fetch_array($select_query)) {
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
$insert_query = mysql_query("INSERT INTO jungle (desk1, chair1, table1) VALUES ('$field1', '$field2', '$field3')", $mysql_connection2);
if ($insert_query) {
echo "Insert Query is OK <br>";
} else {
echo "Insert Query is not OK <br>";
}
}
mysql_close($mysql_connection1);
mysql_close($mysql_connection2);
下面你可以看到表格的示意图。
答案 0 :(得分:1)
您需要建立值吗?
"INSERT INTO jungle (desk1, chair1, table1) VALUES (value1, value2, value3)"
您应该从第一个选择中收集数据,然后您可以在插入语句中设置相关值
您可以使用mysql_fetch
声明
$mysql_connection2 = mysql_connect($host2, $user2, $pass2, true);
mysql_select_db($db2, $mysql_connection2) or die(mysql_error());
while($row = mysql_fetch_array($select_query))
{
$field1 = $row['field1'];
$field2 = $row['field2'];
$field3 = $row['field3'];
$insert_query = mysql_query("INSERT INTO jungle (desk1, chair1, table1) VALUES ('$field1', '$field2', '$field3')",$mysql_connection2);
if ($insert_query) {
echo "Insert Query is OK <br>";
} else {
echo "Insert Query is not OK <br>";
}
}
此语句循环遍历select语句,并使用INSERT
语句为每个返回的结果插入一行
但实际上您还应该查看mysqli
,因为mysql
已弃用。然而,这是你正在做的事情背后的基本逻辑
答案 1 :(得分:1)
为什么不尝试使用mysql Trigger如果你在同一个mysql服务器上,我认为比使用php更有效,你可以看到这个问题以获取更多信息
http://stackoverflow.com/questions/7128173/mysql-trigger-to-insert-data-into-different-db
此处
http://stackoverflow.com/questions/20441783/mysql-create-trigger-insert-content-into-another-database