Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

Insert data from one table to another table using PHP

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In this article, we are going to insert data into another table from the existing table using PHP.


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 “geeks_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 geeks_database
  • Now insert records in table 2 using PHP code from table1.

    PHP Code:


    // creating a connection by passing server name, 
    // username, password and database name
    // servername=localhost
    // username=root
    // password=empty
    // database name= geeks_database
    $connection_link = new mysqli("localhost", "root", "","geeks_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."
        echo "ERROR: Could not able to proceed $sql_query. "
    // Close the  connection 


  • Save this code as copying_data.php under xampp->htdocs folder.
  • Output:

    • Open web browser and type “http://localhost/copying_data.php“.

      data copied image

    • Finally, view your table2. The data is copied from table1 successfully.

My Personal Notes arrow_drop_up
Last Updated : 07 Apr, 2021
Like Article
Save Article
Similar Reads
Related Tutorials