How to insert selected data from a table into another table using php?

2.3k views Asked by At

I want to insert selected data from one of my table under the same database. I have a code but it doesn't work.

moduleindex.php

<?php
    include "connectdatabase.php";//include the connection file
    $db = mysql_select_db("section_masterfile",$connectDatabase);

    $queries = "Select student_Firstname, student_Lastname, student_Section FROM masterfile_table";

    if(isset($_POST['TeacherName'])&& isset($_POST['SectionName']))
    {
     $searchTeacher = $_POST['TeacherName'];
     $searchSection = $_POST['SectionName'];
     $queries = "Select student_Firstname, student_Lastname, student_Section FROM masterfile_table WHERE section_Teacher = '{$searchTeacher}' AND student_Section='{$searchSection}'";
    }

    $queried = mysql_query($queries,$connectDatabase);

?>

insertdata.php

<?php
    include 'moduleindex.php';
    include 'connectdatabase.php';

    $db_pdf = mysql_select_db("section_masterfile",$connectDatabase);


     while($row = mysql_fetch_array($queried))
    {
         $field1 = $row['student_Lastname'];
         $field2 = $row['student_Firstname'];
         $field3 = $row['student_Section'];
         $insert_query = mysql_query("INSERT INTO pdf_table (student_Lastname,student_Firstname,student_Section) VALUES ('{$field1}', '{$field2}', '{$field3}')",$connectDatabase);
     }
?>
2

There are 2 answers

1
Ram Sharma On

You can use single query for both purpose, Try something like this

INSERT INTO pdf_table (student_Lastname, student_Firstname, student_Section )
   SELECT student_Lastname, student_Firstname, student_Section FROM masterfile_table

You can also add the conditions with your select query as per your requirement.

0
Peter Manoukian On

There is a mechanism in sql/mysql called select into, search it on Google.

I am not sure what you are trying to do this is the approach.

  INSERT INTO tbl_temp2 (fld_id)
  SELECT tbl_temp1.fld_order_id
  FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;

As per an example taken from: