i am using INSERT INTO SELECT
Statement Syntax to insert values from another table into my main table
in my php project
x
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name,)n"
. "SELECT subject,n"
. "FROM `subjecttbl`n"
. "WHERE subject_class ='$class' AND subject_session = '2020/2021'";
It worked well but my issue is how to insert variable $student_id along with this on student_resulttbl. pls note $student_id
is not coming from subjecttbl. Its set already. Thank you
Advertisement
Answer
If you want to INSERT
$student_id
to student_resulttbl
table you should do query like this:
INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES (
( SELECT subject FROM `subjecttbl`
WHERE subject_class ='$class'
AND subject_session = '2020/2021'
),
$student_id);
The summary code:
$student_id=1; // dummy id set in a variable
include 'conndb.php';
$sql = "INSERT INTO `student_resulttbl` ( subject_name, student_id ) VALUES ("
. "(SELECT subject FROM `subjecttbl` "
. "WHERE subject_class ='$class' "
. "AND subject_session = '2020/2021'"
. "), $student_id)";
You can INSERT
multiple columns with INSERT INTO
command. More information there:
w3schools.com/sql/sql_insert_into_select.asp
or
https://www.w3schools.com/sql/sql_insert.asp
or
https://www.dofactory.com/sql/insert