Search code examples
phpmysqllastinsertid

Get last record in mysql


Using this php code:

try{
    $dbh = new PDO("mysql:host=$host;dbname=$dbname",$user,$pass);
    $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
    // INSERT CLEAN DATA INTO TABLE…
    $sth = $dbh->prepare("
    INSERT INTO Fan(fanNm,fanEmail,fanPass,fanDynamSalt)
    VALUES('$userName','$userEmailAddress','$userPassword','$dynamSalt')"
    );
    $sth->execute();
    ////////////////////////////////////////////////////////////////////
    ## Set Session Var for this PK ID in Fan table that is being created ##
    ////////////////////////////////////////////////////////////////////
    $_SESSION['newUserSessID'] = mysql_insert_id();
    echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>";
} //try

catch(PDOException $e){
        echo "Oops, We're experiencing an error.";
        file_put_contents('/PDODBConnectionErrors.txt', $e->getMessage(), FILE_APPEND);  
} //catch

It inserts FINE into the database, but I am using echo "<strong style='color:#fff;'>".$_SESSION['newUserSessID']."</strong>"; to echo out that value and it ALWAYS returns a zero.

Even if I run :

SELECT LAST_INSERT_ID( ) 
FROM Fan
LIMIT 0 , 30

It gives me output like

0
0

(since there is two rows in database table)

Anyone?


Solution

  • You should not use mysql_insert_id as that isn't part of PDO (which is what you're using to interact with the database in this instance).

    Instead use PDO::lastInsertId():

    $_SESSION['newUserSessID'] = $dbh->lastInsertId();
    

    More info: http://www.php.net/manual/en/pdo.lastinsertid.php