Sunday, 21 August 2016

Getting ID of Last inserted row in PHP

In web designing there are many reasons when we need to last inserted record id. You can do it with PHP if you will use auto increment in ID. Following code guide you to achieve this.

                                       $servername = "localhost";
$username = "root";
$password = "your password";
$dbname = "your db name";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());

$sql = "INSERT INTO table_name  values(NULL,'$_POST[msg]')";

if (mysqli_query($conn, $sql))
$last_id = mysqli_insert_id($conn);
echo "Record inserted with". $last_id ;

$msg= "Error: " . $sql . "<br>" . mysqli_error($conn);

Next Topic

No comments:

Post a comment