This is what I write when I write a table that imports data from one database to another.
Copy codeThe Code is as follows: <? Php
Header ("Content-type: text/html; charset = UTF-8 ");
$ Conn = mysql_connect ("localhost", "root ","");
Mysql_select_db ('nnd', $ conn );
Mysql_select_db ('ahjk ', $ conn );
Mysql_query ("set names utf8 ");
$ SQL = mysql_query ("select content, partid from phpcms_c_disease order by contentid desc limit
// Here I query the table data and insert it cyclically.
$ Sql1 = "insert into 'nnd'. 'Demo' (content, parid) VALUES ";
While ($ row = mysql_fetch_assoc ($ SQL )){
$ Sql1. = "('$ row [content]', '$ row [partid]'),";
}
$ Sql1. = ")";
$ Sql2. = str_replace (",)", ";", $ sql1 );
Mysql_query ($ sql2 );
?>
I did not expect that I would write such spam code ..
The following describes a better method.
In web development, we often need to insert data from a table to another table. Sometimes, we also need to specify the import field to import records that do not exist in the target table, although these can be split into simple SQL statements in the program, using one SQL statement will save a lot of code. The following uses the mysql database as an example to describe the situation one by one:
1. If the fields of the two tables are consistent and you want to insert all the data, you can use this method:
Insert into target table SELECT * FROM source table; insert into insertTest select * from insertTest2; 2. if you only want to import specified fields, you can use this method: insert into target table (Field 1, Field 2 ,...) SELECT Field 1, Field 2 ,... FROM source table; (the fields must be consistent here) insert into insertTest2 (id) select id from insertTest2; 3. if you want to import only records that do not exist in the target table, you can use this method:
Insert into target table (Field 1, Field 2 ,...) SELECT Field 1, Field 2 ,... FROM source table WHERE not exists (select * from target table where target table. compare field = source table. compare fields );
1> insert multiple records: insert into insertTest2
(Id, name)
Select id, name
From insertTest
Where not exists (select * from insertTest2
Where insertTest2.id = insertTest. id); 2> insert a record: insert into insertTest
(Id, name)
SELECT 100, 'liudehua'
FROM dual
WHERE not exists (select * from insertTest
Where insertTest. id = 100 );