MySQL

How to copy data from one table to another in MySQL using PHP

In this tutorial, we are going to see how to copy data from one table to another in MySQL using PHP. We will specifically use the PDO class. If you are a “newbie” you should know how to connect to a MySQL database before using the code below. You cannot copy data from one table to another if you are not connected to it.
 

How to copy data from one table to another in MySQL using PHP

If you want to copy a table into another, this can be done in MySQL in two steps. The first step is to copy the structure of the table and the second step is to fill the data with the original table.
 

<?php

  //Connect to MySQL using PDO
  $pdo = new PDO($dsn, $user, $password);

  //Name of the table you want to copy.
  $table = 'users';

  //Name of the new table.
  $newTable = 'users_cp';

  //Copy the table structure
  $pdo->query("CREATE TABLE $newTable LIKE $table");

  //Copy the data to the new table
  $pdo->query("INSERT $newTable SELECT * FROM $table");

?>

If you want to check if your new table has been copied, you can check out our tutorial on how to display data from a MySQL table with PHP PDO.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *