Search
 
SCRIPT & CODE EXAMPLE
 

PHP

php pdo last insert id

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

pdo last id


Beware of lastInsertId() when working with transactions in mysql. The following code returns 0 instead of the insert id.



<?php

try {

    $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');



    $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)");



    try {

        $dbh->beginTransaction();

        $tmt->execute( array('user', 'user@example.com'));

        $dbh->commit();

        print $dbh->lastInsertId();

    } catch(PDOExecption $e) {

        $dbh->rollback();

        print "Error!: " . $e->getMessage() . "</br>";

    }

} catch( PDOExecption $e ) {

    print "Error!: " . $e->getMessage() . "</br>";

}

?>



When no exception is thrown, lastInsertId returns 0. However, if lastInsertId is called before calling commit, the right id is returned.
Comment

get last insert id pdo

$(document).ready(function(){
$.ajax({ url: "database/update.html",
        context: document.body,
        success: function(){
           alert("done");
        }});
});
Comment

PREVIOUS NEXT
Code Example
Php :: remove html tags from string php 
Php :: laravel print executed query 
Php :: php previous site 
Php :: deactivate woocommerce breadcrumbs 
Php :: phpexcel set width 
Php :: install php-mbstring in ubuntu 
Php :: laravel collection reverse 
Php :: wordpress fs_method direct 
Php :: get the today data laravel 
Php :: laravel storage symlink 
Php :: laravel generate env 
Php :: laravel route list 
Php :: zsh: command not found: laravel 
Php :: php title case 
Php :: laravel ui auth 
Php :: array to string php 
Php :: php string to int 
Php :: php time format am pm 
Php :: php generate random string fixed length 
Php :: image dimension when uploading in laravel validation 
Php :: composer update without dependencies 
Php :: var_dump _post php 
Php :: get template name wordpress 
Php :: php form action self 
Php :: trim comma from variable in php 
Php :: foreign id laravel migration 
Php :: laravel add values to request 
Php :: pusher-php-server laravel 
Php :: PHP Fatal error: Call to undefined function factory() in Psy Shell code on line 1, LARAVEL 8 Issue solved 
Php :: wordpress echo the excerpt 
ADD CONTENT
Topic
Content
Source link
Name
8+3 =