PHP MySQL tutorial

INSERT INTO SELECT in MySQL

Data stored in a database table can be destroyed or corrupted due to any reason. Therefore, it is convenient to take preemptive measures such as creating backup of data stored in a database table. In MySQL this is done by using INSERT INTO statement in conjunction with SELECT The following syntax is used for copying data from one table to the other in MySQL:


"INSERT INTO 'newtable' SELECT * FROM `oldtable`"

The above code will copy all the data from the oldtable to the newtable. It is important to note here that the schema of both newtable and oldtable should be same. Let’s create backup of the data in our patient table by copying the data into a new table named patient2 which exists in the same database. To do so in mysqli, simply pass the query for copying data to the query function of the mysqli object. Have a look at the following example.




Backing UP Data in Mysqli



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Copying data from one table to the other.

$query = "INSERT INTO `patient2` SELECT * FROM `patient`";
$output = $connection->query($query);

$connection->close();
?>
      



Download the code

<<< GROUP BY and HAVING Clauses in MySQLDEFAULT Statement in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .