version 2
version 2

Reputation: 1059

php- get last insert id

I know this question has been answered many times. I tried a few of the solutions from here but nothing worked. I'm not using any PHP framework.

I have an insert operation taking place and I want to get the id of the inserted row.

Here's my code:

$qry="INSERT INTO tablename(content) VALUES('".$content."')";
setData($qry);

setData() is a user defined function which does insert operation.

//for data submit
function setData($qry)
{
    $obj=new DBCon();
    $res=$obj->submitQuery($qry);
    return $res;
}

//fetches result
function getData($qry)
{
    $obj=new DBCon();
    $res=$obj->selectQuery($qry);
    return $res;
}

This is the class I made for establishing database connectivity:

class DBCon
    {   
        private function getConnection()
        {   
                               // hostname,   username,     password,   database
            $con=mysqli_connect("localhost","root","","dbname")OR die('Could not Connect the Database');        
            return $con;
        }

        public function closeCon()
        {
            mysqli_close($con);
        }

        public function submitQuery($qry)
        {
            $result=0;
            $con=$this->getConnection();
            $result=mysqli_query($con,$qry);
            return $result;
        }

        public function selectQuery($qry)
        {
            $con=$this->getConnection();
            $res=mysqli_query($con,$qry);
            return $res;
        }
    }

To obtain the last inserted id, I wrote the following query but it did not yield any result:

SELECT LAST_INSERT_ID() FROM tablename

Is there any other method to get this?

Upvotes: 5

Views: 15379

Answers (4)

user7978672
user7978672

Reputation:

 $last_id = $conn->insert_id;

Upvotes: 0

Dhiraj Thakur
Dhiraj Thakur

Reputation: 338

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', '[email protected]')";

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();
?>

MySQLi Procedural

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

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

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?> 

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', '[email protected]')";
    // 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;
?> 

Upvotes: 1

Snopzer
Snopzer

Reputation: 1702

LAST_INSERT_ID() only returns values that have been auto-generated by the MySQL server for an AUTO_INCREMENT column; when you insert a specific value, no auto-generation takes place and no value will be returned by LAST_INSERT_ID().

Try : $con->insert_id;

Upvotes: 5

Hiren Makwana
Hiren Makwana

Reputation: 2156

Try This way.

$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 ('First Name', 'Last Name', '[email protected]')";

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;
}

Upvotes: 1

Related Questions