I have a function that creates a course. I am trying to get the Last Insert ID but it doesn’t work:
public function createCourse()
{
require "/mysqli_connect.php";
$course_q = "INSERT INTO course (....) VALUES (.....)";
$course_r = mysqli_query($mysqli, $course_q);
$course_n = mysqli_affected_rows($mysqli);
if($course_n == 1)
{
mysqli_close($mysqli);
return true;
}
mysqli_close($mysqli);
return false;
}
This is the function to retrieve the last insert ID that I created in the same class as the function createCourse:
public function getLastInsertID()
{
require "/../mysqli_connect.php";
$course_q= "SELECT LAST_INSERT_ID()";
$course_r = mysqli_query($mysqli, $course_q);
$course_n = mysqli_num_rows($course_r);
//var_dump($course_n);
if($course_n)
{
$c = mysqli_fetch_assoc($course_r);
mysqli_close($mysqli);
return $c;
}
mysqli_close($mysqli);
return NULL;
}
This is how I call the functions:
require "/mysqli_connect.php";
$course = new Course();
$c = $course->createCourse();
$id = $course->getLastInsertID();
var_dump($id);
"$id" is always "int(0)"
I’ve also tried:
require "/mysqli_connect.php";
$course = new Course();
$c = $course->createCourse();
**$id = mysqli_insert_id($mysqli);**
and I’ve also tried:
$course_q= "SELECT LAST_INSERT_ID() from course";
but that doesn’t work as well. Can you guys see what the problem is? 🙁 The function createCourse itself is fine. It creates what I need and it’s there in the database but I can’t get the last insert id.
Although the proper way to retrieve the insert id with MySQLi is to use
mysqli_insert_id(), since you’re doing an associative fetch, you would need a column alias for theLAST_INSERT_ID()However, that isn’t going to work because you have already closed the connection with
mysqli_close()in yourcreateCourse()function. Instead, get the insert id insidecreateCourse()and return it.Design classes to use one common connection:
The class receives a connection in its constructor.
Include the connection only once on the controlling script