Small series Today I write a table that imports table data from one database to another database.
<?PHPHeader("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//I'm here to query out the table data and then loop into$sql 1= "INSERT into ' nnd '. ' Demo ' (Content,parid) VALUES"; while ($row= Mysql_fetch_assoc ($sql)){ $sql 1. = "(' $row [content] ', ' $row [PartID] '),";}$sql 1.=")";$sql 2. = Str_replace (",)", ";",$sql 1); mysql_query ($sql 2);? >
I never thought I would write such a garbage code in two.
Here's a good way to tell everyone
In web development, we often need to insert data from one table into another, and sometimes we need to specify an import field, which only needs to import records that do not exist in the target table, although these can be broken down into simple SQL in the program, but with one SQL it saves a lot of code. Here I take the MySQL database as an example of the situation explained:
1. If the fields of the 2 tables are consistent and you want to insert all the data, you can use this method:
INSERT into SELECT * from source table; Insert into Select * from InsertTest2;
2. If you want to import only the specified fields, you can use this method:
INSERT into SELECT from source table; (the field must be consistent in this case) Insert into Select from InsertTest2;
3. If you need 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=
1> Insert multiple records:
Insert into insertTest2 (id,name) Select Id,name from inserttest where not exists (Select* from insertTest2where inserttest2.id= Inserttest.id);
2> Insert a record:
Insert into inserttest (ID, name) SELECT - ' Liudehua ' from Dual WHERE not exists (Select* from inserttest where=100 );
Implementation code for inserting a table's data into another table in MySQL