Memar Memar - 4 months ago 8
PHP Question

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

I have three related tables “users”, “category” and “interest_area”; and I want to insert a data from a form into “users” table, and select another data from “category” table and insert into “interest_area” table using PHP.

The error it shows is:


Error: INSERT INTO users(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';
Erreur de syntaxe pr�s de 'INSERT INTO interest_area (category_id) SELECT category_id FROM category ' � la ligne 2


My PHP code is:

<?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;}
}
?>

Answer

You have to run two mysqli_query for insertion

mysqli_query

Better use prepare statement while insertion of data

prepare statement

        $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 should not be blank if it ur primary key then data cann't be inserted;

 $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);