(MySQLi Object-oriented)
[php]
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "accounts";
// Create connection
$connection = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
//Inserting record
$sql = "INSERT INTO users2 (Username, Password, First, Last)
VALUES ('Adam', 'password', 'Adam' , 'Gilchrist')";
if ($connection->query($sql) === TRUE)
{
//Finding id of lastly inserted record
$last_id = $connection->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else
{
echo "Error: " . $sql . "<br>" . $connection->error;
}
$connection->close();
?>
</body>
</html>
[/php]
After inserting the record again, the output will be as follows.
So, the lastly inserted record ID will be
2.
MySQLi Procedural
[php]
<!DOCTYPE html>
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "accounts";
// Create connection
$connection = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
//Inserting record
$sql = "INSERT INTO users2 (Username, Password, First, Last)
VALUES ('Adam', 'password', 'Adam' , 'Gilchrist')";
if (mysqli_query($connection, $sql))
{
//Getting id of lastly inserted record
$last_id = mysqli_insert_id($connection);
echo "New record created successfully. Last inserted ID is: " . $last_id;
}
else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
mysqli_close($connection);
?>
</body>
</html>
[/php]