插入,同时获取id和插入
Insert, get id and insert at the same time
我有两个 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 和英语)
有了mysql
可以使用php函数mysqli_insert_id
(docs)得到最后插入的课程ID,然后就可以把作业添加到它。
$id = createCourse("Maths");
addHomeworkToCourse($id, "Resolve this equation");
让 createCourse return 具有最后插入的 ID 的课程 ID。
php.net/manual/en/mysqli.插入-id.php
这也会使添加的 HomeworkToCourse method/function 更加健壮并且能够在各种情况下使用
我有两个 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 和英语)
有了mysql
可以使用php函数mysqli_insert_id
(docs)得到最后插入的课程ID,然后就可以把作业添加到它。
$id = createCourse("Maths");
addHomeworkToCourse($id, "Resolve this equation");
让 createCourse return 具有最后插入的 ID 的课程 ID。
php.net/manual/en/mysqli.插入-id.php
这也会使添加的 HomeworkToCourse method/function 更加健壮并且能够在各种情况下使用