我有两个PHP函数必须同时执行。我需要使用两个不同的功能,因为例如,我在应用程序中创建一个课程,同时为学生添加多个家庭作业。这是我的简化代码:
function createCourse($courseName) {
global $mysqli,$db_table_prefix;
$stmt = $mysqli->prepare("INSERT INTO courses (name) VALUES (?)");
$stmt->bind_param("s", $courseName);
$result = $stmt->execute();
$stmt->close();
return $result;
}
function addHomeworkToCourse($homeworkDescription) {
global $mysqli,$db_table_prefix;
$course = "13"; // Here comes the problem: how do I get the ID inserted in the previous function
$stmt = $mysqli->prepare("INSERT INTO homework (course, description) VALUES (?, ?)");
$stmt->bind_param("is", $course, $homeworkDescription);
$result = $stmt->execute();
$stmt->close();
return $result;
}
以及在同一页面中创建课程并添加一些家庭作业的表格:
createCourse("Maths");
addHomeworkToCourse("Resolve this equation"); // Add some homework to "Maths"
谢谢你抽出时间!(请注意,我不是PHP、MySQL和英语专家)
$id = createCourse("Maths");
addHomeworkToCourse($id, "Resolve this equation");
让createCourse返回带有上次插入id的课程id。
php.net/manual/en/mysqli.insert-id.php
这也将使addHomeworkToCourse方法/函数更加健壮,并且能够在各种情况下使用
使用mysql
,您可以使用php函数mysqli_insert_id
(docs)获取课程的最后一个插入ID,然后您可以向其中添加作业。