How do I get the last inserted ID of a MySQL table in PHP?

How do I get the last inserted ID of a MySQL table in PHP?


Method 1:
If you use php to connect to mysql you can use mysql_insert_id() to point to last inserted id.

mysql_query("INSERT INTO mytable (1, 2, 3, 'blah')");
$last_id = mysql_insert_id();

Method 2:MySQLi Object-oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

Method 3:

PDO


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com')"
;
    // use exec() because no results are returned    $conn->exec($sql);
    $last_id = $conn->lastInsertId();
    echo "New record created successfully. Last inserted ID is: " . $last_id;
    }
catch(PDOException $e)
    {
    echo $sql . "<br>" . $e->getMessage();
    }

$conn = null;
?>


Simple:
mysql_query('INSERT INTO FOO(a) VALUES(\'b\')');
$id = mysql_insert_id();


How do I get the last inserted ID of a MySQL table in PHP? How do I get the last inserted ID of a MySQL table in PHP? Reviewed by Anonymous on February 18, 2017 Rating: 5

No comments:

Java Ternary Operator

Java Ternary Operator Java ternary operator is the only conditional operator that takes three operands. Java ternary operator is a one l...

Powered by Blogger.