简体   繁体   中英

PHP Insert data from one table to another

I was trying to insert the data from one table to another, and this is the error message I get:

Error: INSERT INTO content2 (d1, d2, d3) VALUES (John, Doo, 24);

Unknown column 'John' in 'field list'Error: INSERT INTO content2 (d1, d2, d3) VALUES (Mary, Moe, 36);

Unknown column 'Mary' in 'field list'Error: INSERT INTO content2 (d1, d2, d3) VALUES (Julie, Dooley, 42)

Unknown column 'Julie' in 'field list'Error: INSERT INTO content2 (d1, d2, d3) VALUES (John, Doo, 24);

Unknown column 'John' in 'field list'Error: INSERT INTO content2 (d1, d2, d3) VALUES (Mary, Moe, 36);

Unknown column 'Mary' in 'field list'Error: INSERT INTO content2 (d1, d2, d3) VALUES (Julie, Dooley, 42);

Unknown column 'Julie' in 'field list'

Here is my php code:

//Get Connection
require_once('connect.php');

//Get Data
$sql = "SELECT d1, d2, d3 FROM content";
$result = mysqli_query($con, $sql);

if (mysqli_num_rows($result) > 0) {
// output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $row1 = $row["d1"];
        $row2 = $row["d2"];
        $row3 = $row["d3"];

//Insert Data to another table
            $sql = "INSERT INTO content2 (d1, d2, d3)
            VALUES ($row1, $row2, $row3);";
            if (mysqli_multi_query($con, $sql)) {
                echo "New records created successfully";
            } else {
                echo "Error: " . $sql . "<br>" . mysqli_error($con);
            }
        //echo "id: " . $row["d1"]. " - Name: " . $row["d2"]. " " . $row["d3"]. "<br>";
    }
} else {
    echo "0 results";
}

I couldn't figure out what the problem are. Please Help

When PHP sends your insertion query to MySQL, it ends up looking like this:

INSERT INTO content2 (d1, d2, d3) VALUES (John, Mary, Julie);

Because there are no quotation marks around “John”, “Mary”, and “Julie”, MySQL thinks you're referring to other column names. The quick and dirty solution would be to add quotation marks to your query, but as @tadman says, you should not ever be using this style of query, and should instead use bind_param to add your variables to the query.

However, if all you want to do is copy from one table to another, as @Dan Bracuk says, you can do this with a single query:

INSERT INTO content2 (d1, d2, d3)
SELECT d1, d2, d3
FROM content

This can be done with straight sql.

insert into content2
(d1, d2, d3)
select d1, d2, d3
from content

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM