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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.