![](/img/trans.png)
[英]Select data from db table 1 and insert it into another db table 2 in php
[英]I want to insert a data from a form into a table, and select another data from another table and insert into third table using PHP
我有三個相關的表“用戶”,“類別”和“ interest_area”; 我想將表單中的數據插入“用戶”表中,並從“類別”表中選擇另一個數據,然后使用PHP插入“ interest_area”表中。
它顯示的錯誤是:
錯誤:INSERT INTO用戶(user_id,first_name,last_name,higher_education,user_name,pass_word)VALUES('','87878787','iuiu','iuiu','root',''); INSERT INTO interest_area(category_id)SELECT category_id從類別WHERE category_name ='ASP'; 在'INSERT INTO interest_area(category_id)中選擇類目ID從FROM類別'-la ligne 2
我的PHP代碼是:
<?php
if (isset($_POST["interest_area"])){
$f_name = $_POST["firstname"];
$l_name = $_POST["last_name"];
$h_education = $_POST["higher_education"];
$i_area = $_POST["interest_area"];
$email = $_POST["email"];
$u_name = $_POST["user_name"];
$p_word = $_POST["pass_word"];
$sql = "INSERT INTO users(user_id, first_name, last_name, higher_education, user_name, pass_word)
VALUES('' , '$f_name' , '$l_name' , '$h_education' , '$username' , '$password');";
$sql .= "INSERT INTO interest_area (category_id)
SELECT category_id FROM category
WHERE category_name = '$i_area';";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";}
else { echo "Error: " . $sql . "<br>" . $conn->error;}
}
?>
您必須運行兩個mysqli_query進行插入
插入數據時更好地使用prepare語句
$f_name = $_POST["firstname"];
$l_name = $_POST["last_name"];
$h_education = $_POST["higher_education"];
$i_area = $_POST["interest_area"];
$email = $_POST["email"];
$u_name = $_POST["user_name"];
$p_word = $_POST["pass_word"];
$user_id = $_POST["user_id"];
$user_id
如果它是您的主鍵,則不能插入數據;
$sql1 = "INSERT INTO users(user_id, first_name, last_name, higher_education, user_name, pass_word)
VALUES('$user_id' , '$f_name' , '$l_name' , '$h_education' , '$u_name' , '$p_word')";
$sql2 = "INSERT INTO interest_area (category_id)
SELECT category_id FROM category WHERE category_name = '$i_area'";
mysqli_query($con,$sql1);
mysqli_query($con,$sql2)
mysqli_close($con);
您只需要將兩個INSERT
語句作為單獨的$conn->query
調用運行,而不是將它們串聯為一個調用。
語法錯誤在這里:
$sql .= "INSERT INTO interest_area (category_id)
SELECT category_id FROM category
WHERE category_name = '$i_area';";
應該是卷曲的...
$sql .= "INSERT INTO interest_area (category_id)
SELECT category_id FROM category
WHERE category_name = {$i_area};";
以及如所述的兩個獨立的查詢...
您需要對多個查詢使用multi_query。
$sql = "INSERT INTO users(user_id, first_name, last_name, higher_education, user_name, pass_word)VALUES('' , '$f_name' , '$l_name' , '$h_education' , '$username' , '$password');";
$sql .= "INSERT INTO interest_area (category_id)
SELECT category_id FROM category WHERE category_name = '$i_area'";
mysqli_multi_query($con,$sql);
mysqli_close($con);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.