Select all data from a table and insert it to anot

2019-08-30 00:05发布

问题:

I wanted to select all the data from one of my table and insert it to another table. I have this code but it wasn't working..This is what the phpMyadmin says "MySQL returned an empty result set (i.e. zero rows). (Query took 0.0010 seconds.)"

Here is my code:

if(isset($_POST['select_table']))
{
    $select_table = mysql_real_escape_string($_POST['select_table']);
    $query_select = "INSERT INTO pdf_table
                    SELECT * FROM $select_table";
    $select_query = mysql_query($query_select,$connectDatabase);
}

回答1:

Please ensure that both the tables have equal number of columns. It is a good practice to use following way for inserting records with select query :-

INSERT INTO pdf_table (column_1, column_2) SELECT column_1, column_2 FROM $select_table


回答2:

your sql query is like

INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1; 


回答3:

The approach you are using INSERT INTO pdf_table SELECT * FROM $select_table will give you only single row inserted from 1st table to another table.

As per your requirement you want all the records from 1st table should get insert in your pdf_table So i will like to suggest try the following approach May be this is what you looking for

if(isset($_POST['select_table']))
{
    $select_table = mysql_real_escape_string($_POST['select_table']);

    $select_query = mysql_query( "select * from $select_table ",$connectDatabase);

    while ($row = mysql_fetch_array($select_query))
    {
         mysql_query( "insert into pdf_table values($row['column1'],$row['column2'],...,$row['columns']) ",$connectDatabase);

    }

}


回答4:

try this one :

if(isset($_POST['select_table']))
{
    $select_table = mysql_real_escape_string($_POST['select_table']);
    $query_select = " Create Table pdf_table ( SELECT * FROM $select_table); ";
    $select_query = mysql_query($query_select,$connectDatabase);
}

but, this query will create new table "pdf_table".