我有兩個表questions
和answers
,並希望使用PHP將每個表的行復制到同一個表中。該表的結構如下:在MySQL中,如何複製使用PHP的同一表中的兩個表的行?
表:問題
表:回答
目前我使用下面的代碼,但它是不工作:
include "db.php";
$exam_title=$_POST["title_id"];
$exam_id=$_POST["exam"];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "insert into questions(question, option_type, media_type, media_link, exam_id)
select question, option_type, media_type, media_link, '$exam_id' from questions where exam_id = ". $exam_id;
$sql2 = "insert into answers(answer, ques_id, right_ans)
select a.answer, q.ques_id, a.right_ans from questions q, answers a where q.exam_id = ". $exam_id;
if ($conn->query($sql) === TRUE) {
echo "done";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
if ($conn->query($sql2) === TRUE) {
echo "done2";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
的問題是questions
表ques_id
和ans_id
的answers
表primary key
是auto increment
其中answers
和questions
ques_id
ques_id
有關係。
什麼錯誤你會得到嗎? – Clay
它正在返回done2(成功消息),但東西沒有被複制。 –
也許autocommit被禁用。這就是爲什麼你應該在關閉連接之前提交。 –