PHPSuperBlog.com

Copy one table’s field records into another table’s field in MySQL database with PHP

Editor’s note: In some cases such as a login system or other company’s stock count system which the records in the MySQL database might need to update very frequently. There might be a need to create another tables to backup monthly of the data to another table in the MySQL database. It is a good idea to copy one table’s field records to another table’s field.

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 ();	
}
?>
VN:F [1.9.3_1094]
Rating: 10.0/10 (1 vote cast)
VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)
Copy one table's field records into another table's field in MySQL database with PHP, 10.0 out of 10 based on 1 rating

Similar Posts:

Leave a comment