Pdo Get the Last Id Inserted

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

PDO - get current inserted ID

$query = "INSERT INTO news VALUES (NULL, :param1 , :param2  )";
$stmt = $pdo->prepare($query);

$params = array(
"param1" => $p['title'],
"param2" => $p['body'],
);

$data = $stmt->execute($params);

so you can do like this to get last inserted Id

$last_id = $pdo->lastInsertId();

How to get last inserted inserted row id from PDO

You're almost there.

If you look at the manual page for lastInsertId, it's called on the database handle - you're currently calling it on the statement.

You just need to call:

$this->db->lastInsertId();

How to access last inserted id in PDO with static variable?

UPDATE:

Simple way to use the lastInsertId() is:

// your connection with database
$con = new PDO("mysql:host=$hostname;dbname=$dbname",$dbuser,$dbpass);

// insert query
$query = "INSERT INTO tbl_name SET col_name1 = ?, col_name2 = ?";
// '$con' is your PDO connection variable
$stmt = $con->prepare($query);
$stmt->bindParam(1, $variable1); // value for col_name1 to be stored
$stmt->bindParam(2, $variable2); // value for col_name2 to be stored
$stmt->execute();
....
// gives current inserted id
$lastId = $con->lastInsertId();

In your case try: $lastId = connection::$pdo->lastInsertId();

Getting the id of the last inserted record from an MSSQL table using PDO and PHP

If your id column is named id you can use OUTPUT for returning the last inserted id value and do something like this:

    $CustID = "a123";
$Name="James"
$stmt = "INSERT INTO OrderHeader (CustID, Name)
OUTPUT INSERTED.id
VALUES (:CustID, :Name)";

$stmt = $db->prepare( stmt );
$stmt->bindParam(':CustID', $CustID);
$stmt->bindParam(':Name', $Name);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result["id"]; //This is the last inserted id returned by the insert query

Read more at:

https://msdn.microsoft.com/en-us/library/ms177564.aspx

http://php.net/manual/es/pdo.lastinsertid.php



Related Topics



Leave a reply



Submit