Question

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?

Was it helpful?

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top