我有三个相关的表“users”,“category”和“interest_area”;我想将表单中的数据插入“users”表,然后从“category”表中选择另一个数据,并使用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 FROM category WHERE category_name =' ASP&#39 ;; Erreur desyntaxepr�sde' INSERT INTO interest_area(category_id)SELECT category_id FROM category' �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;}
}
?>
答案 0 :(得分:1)
你必须运行两个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);
答案 1 :(得分:0)
您只需将两个INSERT
语句作为单独的$conn->query
调用运行,而不是将它们连接成一个调用。
答案 2 :(得分:0)
语法错误在这里:
$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};";
如上所述两个单独的查询...
答案 3 :(得分:0)
您需要将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);