In this article, we are going to insert data into another table from the existing table using PHP.
Requirements:
PHP stands for Hypertext preprocessor. MySQL is a database query language for performing database operations. We are going to insert data from one table into another table by using MySQL Server.
MySQL server is an open-source relational database management system that is used for web applications.
-
Insert query syntax:
insert table_2 select * from table_1.
Follow the below Steps:
- Open XAMPP server and start Apache and MySQL.
- Open your browser and type “localhost/phpmyadmin”. Create a database named “neveropen_database”
- Now create a table named table1 with 4 columns and click on save.
- Now open the SQL column in the database server and insert records into it.
MySQL code: The following are the SQL statements to insert data in table1.
INSERT INTO `table1`(`name`, `address`, `country`, `city`) VALUES (‘sravan’,’kakumanu’,’india’,’guntur’);
INSERT INTO `table1`(`name`, `address`, `country`, `city`) VALUES (‘sudheer’,’chebrolu’,’india’,’guntur’);
INSERT INTO `table1`(`name`, `address`, `country`, `city`) VALUES (‘vani’,’kakumanu’,’india’,’guntur’);
INSERT INTO `table1`(`name`, `address`, `country`, `city`) VALUES (‘radha’,’tenali’,’india’,’guntur’);Output: The table1 includes the following data.
- Write create table2 in XAMPP SQL server in the same database neveropen_database
- Now insert records in table 2 using PHP code from table1.
PHP Code:
PHP
<?php
// creating a connection by passing server name,
// username, password and database name
// servername=localhost
// username=root
// password=empty
// database name= neveropen_database
$connection_link
=
new
mysqli(
"localhost"
,
"root"
,
""
,
"neveropen_database"
);
if
(
$connection_link
=== false) {
die
(
"ERROR: Not connected. "
.
$connection_link
->connect_error);
}
//sql query to perform copying data from one table to another
$sql_query
=
"insert table2 select * from table1"
;
if
(
$connection_link
->query(
$sql_query
) === true)
{
echo
"Data Copied Successfully."
;
}
else
{
echo
"ERROR: Could not able to proceed $sql_query. "
.
$connection_link
->error;
}
// Close the connection
$connection_link
->close();
?>
- Save this code as copying_data.php under xampp->htdocs folder.
-
Output:
- Open web browser and type “http://localhost/copying_data.php“.
- Finally, view your table2. The data is copied from table1 successfully.