Get the last inserted ID using PHP MySQLi function
This article briefly introduces the PHP mysqli()
function and demonstrates how to use it to get the last inserted ID from a MySQL database.
PHP mysqli() Function
It is an extended version of the MySQL driver called mysqli and is typically used with PHP server-side scripts to connect to a MySQL database or schema.
First, you must connect to your MySQL database. The connect()
or mysqli_connect()
function is used to open a connection to a MySQL server.
Before using this function, you must create mysqli()
a object that contains parameters about your MySQL server.
<?php
$mysqli = new mysqli(
"host_name",
"username",
"password",
"database_name",
"port",
"socket"
);
//Checking connection
if ($mysqli -> connect_errno){
echo "Something went wrong. Failed to connect with MySQL database".
$mysqli -> connection_error;
exit();
}
else{
echo "Connected";
}
?>
If the connection is not established, the above code will notify the user; otherwise, it will print connected on the browser screen.
Parameter Description
parameter | illustrate |
---|---|
host_name | Specify a host name (for example: localhost) or an IP address. |
username | Specify your MySQL database username. |
password | Specify the password for your MySQL database. |
database_name | Provide the name of the database or schema to which you want to connect in the MySQL database. |
port | Used to connect to the MySQL server. |
socket | Specifies a socket or named pipe. |
Get the last inserted ID using PHP mysqli() function
To accomplish this task, you must create a table with an AUTO_INCREMENT field that will return the last inserted record ID.
Why is there AUTO_INCREMENT? Auto-increment automatically creates a unique number whenever a new record is inserted into a table.
It is usually the primary key field that we want to automatically generate every time a new record is inserted. See the following code to understand how we create an AUTO_INCREMENT column:
CREATE TABLE table_name(
column_name1 INT AUTO_INCREMENT PRIMARY KEY,
column_name2 VARCHAR(100)
);
An INT column will store integer values, while AUTO_INCREMENT will automatically increase the value of the column when new records are inserted. Finally, the PRIMARY KEY sets a constraint that only allows unique values for the column.
The second column is of type VARCHAR which can accept string values. To get the last inserted id, mysqli() provides the insert_id command; check it out below:
$mysql->insert_id;
To see this command in action, first, run an INSERT query, then run the insert_id command to see the last inserted ID:
<?php
$mysqli = new mysqli(
"host_name",
"username",
"password",
"database_name",
"port",
"socket"
);
// Checking connection
if ($mysqli -> connect_errno){
echo "Something went wrong. Failed to connect with MySQL database".
$mysqli -> connection_error;
exit();
}else{
echo "Connected";
}
$sql_query = "INSERT INTO table_name (column_name2) VALUES ('value_2')";
if ($mysqli->query($sql_query) === TRUE) {
printf("Last inserted record ID %d. \n", $mysqli->insert_id);
} else {
echo "Error: ". $sql_query . "<br>" . $mysqli->error;
}
?>
In the above code, $mysqli -> query()
the function executes the given query against the selected database and compares the return values.
If TRUE, we use printf()
the function to output the formatted string; otherwise, it uses $mysqli -> error
to print errors.
The arguments you supply to printf()
the function are inserted into the original string you supply after the % sign. The %d sign indicates that the value to be inserted is a signed decimal number (negative, positive, or zero).
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Changing max_allowed_packet Size in MySQL Server
Publish Date:2025/04/22 Views:192 Category:MySQL
-
This article explains how to change the max_allowed_packet size in MySQL server. To understand this, we will use two operating systems, Windows 10 and Linux (Ubuntu). Changing max_allowed_packet Size in MySQL Server If we try to upload a fi
Zerofill usage, advantages and alternatives in MySQL
Publish Date:2025/04/22 Views:195 Category:MySQL
-
In this article we will understand the uses, advantages and alternatives of ZEROFILL attribute in MySQL. Use and benefits of the ZEROFILL attribute in MySQL The benefit of using the ZEROFILL attribute is that it has nothing to do with input
Compare only MySQL timestamp dates to date parameters
Publish Date:2025/04/22 Views:64 Category:MySQL
-
In this article we will use the DATE() , CAST() , and CONVERT() functions to compare MySQL timestamp dates with only the date parameter. DATE() vs. CAST() vs. CONVERT() in MySQL Below is a brief description of each function. You can also fi
Calculating Percentages in MySQL
Publish Date:2025/04/22 Views:66 Category:MySQL
-
We will use one or more columns to calculate percentages in MySQL. There are different ways to do this, and for each method we will use an example table. Calculate percentage using a column in MySQL We have a table called sales where ID, Re
Selecting multiple values using WHERE in MySQL
Publish Date:2025/04/22 Views:185 Category:MySQL
-
This article is about using MySQL query to get data from a specific table or relation that satisfies a specific condition. To do this, the WHERE clause is used in the SQL query. WHERE clause in SQL query WHERE The clause specifies the condi
Changing the connection timeout in MySQL
Publish Date:2025/04/22 Views:59 Category:MySQL
-
We are learning how to change the connection timeout in MySQL using Linux (Ubuntu 20.04) and Windows operating systems. Changing the connection timeout in MySQL Sometimes you keep losing connection to the MySQL server because the connect_ti
MySQL fix Data Is Truncated for a Column error
Publish Date:2025/04/22 Views:101 Category:MySQL
-
This article describes possible causes and solutions for the MySQL error Data is truncated for a column . Fix data truncated due to column error in MySQL Here, we will discuss the possible causes and solutions to eliminate MySQL data trunca
MySQL Error Server PID File Could Not Be Found Solution
Publish Date:2025/04/22 Views:192 Category:MySQL
-
In this article, we will study about the Error! Error Server PID File Could Not Be Found! in MySQL and its solution with full explanation. MySQL PID file The file that contains the process identification number or process ID of a running My
Installing MySQL Client in Linux
Publish Date:2025/04/22 Views:186 Category:MySQL
-
MySQL is an abbreviation for Structured Query Language which is a relational database management system. It is an open source database which is freely available and used for both large and small applications. The use cases are in school app