2015-03-24 154 views
0

我有两个PHP函数必须同时执行。我需要使用两种不同的功能,例如,我在我的应用程序中创建课程,同时为学生添加多项作业。这里是我的简化代码:插入,获取ID并同时插入

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和英文)

+1

,什么是使用php.net/manual/en/mysqli.insert-id.php

这也将使加HomeworkToCourse方法/功能更强大,能够这个问题? – 2015-03-24 21:36:19

+1

您是否可以修改第一个函数以返回如果成功插入的最后一行的ID。然后您可以将此值传递给第二个函数。 http://php.net/manual/en/mysqli.insert-id.php。您将不得不修改第二个函数以添加另一个参数,该参数将成为您添加作业说明的课程的ID。 – Maximus2012 2015-03-24 21:37:10

+0

@ Maximus2012我尝试了mysqli_insert_id,但它什么都没有返回(我不知道我是否做错了什么) – 2015-03-24 22:14:13

回答

2
$id = createCourse("Maths"); 
addHomeworkToCourse($id, "Resolve this equation"); 

让createCourse返回最后插入ID的课程ID。

在各种情况下

+0

非常感谢! – 2015-03-24 22:32:28

0

随着mysql您可以使用PHP函数mysqli_insert_iddocs),以获得该课程的最后插入的ID,那么你可以将作业添加到它。

+0

我隐瞒了你在评论之前编辑了我的错字。该链接始终指向文档 – Scopey 2015-03-24 21:41:06

+0

中的mysqli版本...并且我悄悄地删除了该评论。 – 2015-03-24 21:48:31