Marcel Wasilewski
Marcel Wasilewski

Reputation: 2679

INSERT table into other table with more columns using PHP

i want to insert a database table into another one which has more columns. I need all records of it. What i tried is following which is not working and does not give me an error message:

 $sql = mysqli_query($con, "SELECT * FROM table1");

 while ($row = mysqli_fetch_array($sql)) {
        $sql1 = mysqli_query($con, "INSERT INTO table2
                                    (uid,
                                    pid,
                                    tstamp,
                                    crdate)
                                   VALUES ('',
                                          '".$row['value1']."',
                                          '".$row['value2']."',
                                          '".$row['value3']."'");}

Upvotes: 1

Views: 50

Answers (2)

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

you can directly do it like this, that's much faster and better than fetching the data and iterating over it.

 insert into table2(uid,pid,tstamp,crdate) 
 select value1,value2,value3,value4 from table1

Upvotes: 4

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

you forget close " :

 mysqli_query($con, "INSERT INTO table2
                                    (uid,
                                    pid,
                                    tstamp,
                                    crdate)
                                   VALUES ('',
                                          '".$row['value1']."',
                                          '".$row['value2']."',
                                          '".$row['value3']."');");

also you can do this in query by select into to reduce consuming time:

INSERT INTO table2 (uid,pid,tstamp,crdate)
SELECT '',val1,val2,val3 FROM table1;

Upvotes: 1

Related Questions