Jump to content

PDO::lastInsertId


doddsey_65

Recommended Posts

im trying to get the last inserted id from the database so when the user makes a post i can reload the page and center it on their post via the url hash(http://website/posts#221)

 

however everytime i try this i get a result of 0. here is my code:

 

$link->query("INSERT INTO ".TBL_PREFIX."posts
                (p_fid, p_tid, p_poster, p_name,
                p_content, p_time_posted)
                VALUES
                ('$forum_id', '$topic_id', '$user_name',
                '$subject', '$message', '".$config['time_now']."')
                ") or die(print_link_error());
echo $link->lastInsertId();

 

its just a simple insert query(which works as expected) but the lastInsertId function returns 0. where am i going wrong?

Link to comment
https://forums.phpfreaks.com/topic/227966-pdolastinsertid/
Share on other sites

PHP Site about the PDO::lastInsertID

Note:

 

This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.

 

Try doing a prepare() and then pulling the lastInsertID before committing.

 

Link to comment
https://forums.phpfreaks.com/topic/227966-pdolastinsertid/#findComment-1175523
Share on other sites

Thanks for the info. This worked fine:

 

$insert = $link->prepare("INSERT INTO ".TBL_PREFIX."posts
                (p_fid, p_tid, p_poster, p_name,
                p_content, p_time_posted)
                VALUES
                ('$forum_id', '$topic_id', '$user_name',
                '$subject', '$message', '".$config['time_now']."')
                ") or die(print_link_error());
        
        $insert->execute();
        
        $lid = $link->lastInsertId();

Link to comment
https://forums.phpfreaks.com/topic/227966-pdolastinsertid/#findComment-1175526
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.