简体   繁体   中英

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?

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

You're mixing PDO with generic MySQL functions. The problem is the mysql_last_insert has no resource, and so it returns 0 for false. Don't mix PDO with generic MySQL functions.

To get the last insert id in PDO, do this: $dbh->lastInsertId()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM