Copy one table’s field records into another table’s field in MySQL database with PHP
Here I have created an example on how to copy one table’s field records into another table’s field in MySQL database.
I have created a PHP file, I called it “test.php”
In the MySQL database, I have created a database with a table named “source” and another table called “destination”.
Table “source” has a field named “name” and has 3 records “TOM”,”JOHN”,”MARY” in it, see table below:
| name |
| TOM |
| JOHN |
| MARY |
Table “destination” has a field named “user” and has no records in it.
The point of this is to copy the 3 records of the field “name” of the table “source” into the field “user” of the table “destination”.
And here are the codes of the PHP file “test”:
First we have to connect to the database:
mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed");
Then we create a query to select all records from table “source”:
$query = "SELECT * FROM source";
Now we run the query:
$result = mysql_query($query);
We now start a while loop record by record until the record does not meet the criteria of the query above, in this case the query is to select all records from the table “source” which means the while loop will end until all records have done:
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { ........ }
Now we put operations inside the while loop for each records, in this case we create another query to insert each record from the field “name” of the table “source” into the field “user” of the table “destination”:
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { mysql_query("insert into destination(user) VALUES ('$line[name]')")or die (); }
All together, we have:
<?php mysql_connect("Host Name", "User Name", "User Password") or die("Connection Failed"); mysql_select_db("DataBase Name")or die("Connection Failed"); $query = "SELECT * FROM source"; $result = mysql_query($query); while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) { mysql_query("insert into destination(user) VALUES ('$line[name]')")or die (); } ?>
Similar Posts:
- Merging 2 MySQL tables with PHP – update one table’s field with another table’s field data (both table have one common field)
- Display data from MySQL with PHP
- Get MySQL database records as HTML form text field’s value
- Create check box by using the records from MySQL datebase as values
- Display data from MySQL database with HTML form and PHP






