How can I insert data from a table to another table after the clicking of a button using PHP and MySQL?
Asked
Active
Viewed 48 times
-4
-
make one php function that runs on button click , inside that function , write a SQL query for retriveing record from one table , then write SQL query for insert that record in to other table – Saurabh Mistry Sep 20 '18 at 05:27
-
Stackoverflow isn't a coding service. We don't code for you. If make a simple search on google you can find a lot of tutorials. So try something, show us what you have tried and then ask a question. [mcve] – Sfili_81 Sep 20 '18 at 07:07
2 Answers
0
I think this takes a little more than a simple answer, try reading a php-mysql tutorial: https://www.w3schools.com/Php/php_mysql_intro.asp
In plain Mysql you just need a "insert into" statement with a select, as explained here. Then you'll just need to create a php statement to execute this SQL.

patrick
- 55
- 1
- 6
0
Following php script can be used to fetch values from one Table and insert data into another table:
<?php
$servername = "localhost"; //if running on localhost
$username = "root"; // if running on localhost
$password = ""; // empty for mysql default password
$dbname = "database name";
$conn = mysqli_connect($servername, $username, $password,$dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['name of button'])) { // if button is clicked the following code will be executed
$sql_db1 = "SELECT * FROM `table_name_1` WHERE condition"; // if you want to select data based on some constraint.
$sql_db1_query = mysqli_query($conn,$sql_db1); // mysqli_query takes 2 parameters -> connection to database and sql query.
while($row = mysqli_fetch_array($sql_db1_query)){
$sql_db2 = "INSERT INTO `table_name_2`(`column1`,`column2`,`column3`,`column4`) VALUES($row['column1'],$row['column2'],$row['column3'],$row['column4'])"; //'column1' inside $row[] and so on should be replace by the column names of the table in which you want to insert the data
$sql_query_db2 = mysqli_query($conn,$sql_db2);
}
}
?>

prashant bana
- 175
- 8