doddsey_65 Posted February 17, 2011 Share Posted February 17, 2011 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 More sharing options...
cgsmith105 Posted February 17, 2011 Share Posted February 17, 2011 Hey doddsey_65! Going to have to see what lastInserID() does! If you are using mysql you can use the mysql_insert_id() function. That will give you the ID of the most recent query performed. Link to comment https://forums.phpfreaks.com/topic/227966-pdolastinsertid/#findComment-1175513 Share on other sites More sharing options...
doddsey_65 Posted February 17, 2011 Author Share Posted February 17, 2011 im using PDO not mysql Link to comment https://forums.phpfreaks.com/topic/227966-pdolastinsertid/#findComment-1175517 Share on other sites More sharing options...
cgsmith105 Posted February 17, 2011 Share Posted February 17, 2011 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 More sharing options...
doddsey_65 Posted February 17, 2011 Author Share Posted February 17, 2011 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.