This is what I wrote today when I wrote a table that would import a database's table data into another database.
Copy Code code 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
I'm here to query out the data for the table and then loop it 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 didn't think I would be so two to write this garbage code.
Here's a better way to say
in web development, we often need to insert data from one table into another, and sometimes we need to specify an import field that only needs to import records that don't exist in the target table, although they can be split into simple SQL in a program, but with one SQL, you save a lot of code. Here I take the MySQL database as an example of a description:
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 target table SELECT * from source table;
Insert INTO inserttest select * from insertTest2;
2. If you want to import only the specified fields, you can use this method:
INSERT into Destination 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. You can use this method if you need to import only records that do not exist in the destination table:
SELECT Field 1, Field 2, ...
WHERE NOT EXISTS (SELECT * from Target table)
where target table. comparison field = Source table. comparison field);
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&NBSP;&NBSP;&NBSP;&NBSP
(id, name)
select 100, ' Liudehua '
from dual
WHERE not exists ( select * from inserttest &NBSP
where inserttest.id = +)