I am trying to perform an insert with the information of a query from another table, using php and mysql, I know that I have not done the protection part against sql injection correctly, I will solve that at the end, I tell you why then they only go to scold and do not contribute, would you be kind enough to tell me how to use the value obtained from the query, thank you.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include("conection.php");
$credits = mysqli_real_escape_string($con, $_POST['credits']);
$namesec = mysqli_real_escape_string($con, $_POST['namesec']);
$change = mysqli_real_escape_string($con, $_POST['change']);
$stmt = $con->prepare("UPDATE students
SET student_credits = (student_credits ?)
WHERE student_qr = $?");
$stmt->bind_param("is", $_POST['credits'], $_POST['namesec']);
$stmt->execute();
$insert_query = $con->prepare("INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?"
);
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();
mysqli_close($con);
?>
I want to use the value of id_student obtained from the query to insert it into a new table
CodePudding user response:
You forgot to call fetch_assoc()
to get the row that the query returns.
You also didn't quote $namesec
in the SELECT
query, so it's getting an error. This wouldn't be a problem if you used a parameter instead of substituting the variable.
But there's no need to do this in two queries. You can give a SELECT
query as the source of the data in INSERT
.
$insert_query = $con->prepare("
INSERT INTO historical_credits (id_students, credits_paid)
SELECT id_students, ?
FROM students
WHERE student_qr = ?");
$insert_query->bind_param("is", $_POST['credits'], $_POST['namesec']);
$insert_query->execute();