How can the last inserted ID be retrieved and used as a parameter in a PHP function?
To retrieve the last inserted ID and use it as a parameter in a PHP function, you can use the `mysqli_insert_id()` function to get the ID of the last inserted record in a MySQL database. You can then pass this ID as a parameter to your PHP function for further processing.
// Connect to the database
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Insert a record into the database
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; // Get the last inserted ID
// Call a function and pass the last inserted ID as a parameter
your_function($last_id);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Close the database connection
$conn->close();
// Function that uses the last inserted ID
function your_function($id) {
// Use the last inserted ID for further processing
echo "Last inserted ID: " . $id;
}