我有两个必须同时执行的 PHP 函数。我需要使用两个不同的功能,因为例如,我在应用程序中创建一门类(class),同时为学生添加多个作业。这是我的简化代码:
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;
}
以及在同一页面中创建类(class)并添加一些作业的表单:
createCourse("Maths");
addHomeworkToCourse("Resolve this equation"); // Add some homework to "Maths"
感谢您的宝贵时间! (请注意,我不是 PHP、MySQL 和英语专家)
最佳答案
$id = createCourse("Maths");
addHomeworkToCourse($id, "Resolve this equation");
让createCourse 返回最后插入的类(class)的id。
php.net/manual/en/mysqli.insert-id.php
这也将使 add HomeworkToCourse 方法/函数更加健壮,并且能够在各种情况下使用
关于php - 插入、获取id、同时插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29243337/