• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[SOLVED]Problem tracking a database value

I am trying to insert a new forum topic into a forum. When the user clicks the add_topic submit button and has all their fields filled in this code will execute. What it is doing is adding a topic title, topic_poster_id and topic submitted time into a topic table in a database. Also the post_subject and topic_id is inserted into a posts table in a database. Problem is, how do I know what the topic_id will be when I insert the topic_id into the post table?

$this->db->insert('sb_topics' array( 'topic_title' => $post_subject, 'topic_poster_id' => $this->session->userdata('id'), 'topic_time' => NOW(), 'forum_id' => $this->uri->segment(3) ))
$this->db->insert('sb_posts' array( 'post_subject' => $post_subject, 'post_message' => $post_message, 'poster_id' => $this->session->userdata['id'], 'topic_id' => $topic_id ) )

[eluser]Armchair Samurai[/eluser]
Cleaned for readability. Also, you may want to change that SQL NOW() to date('H:iConfused') because I'm pretty sure that with CI escaping, it might not do what you want it to.
    'topic_title' => $post_subject,
    'topic_poster_id' => $this->session->userdata('id'),
    'topic_time' => NOW(),
    'forum_id' => $this->uri->segment(3)

$topic_id = $this->db->insert_id();

    'post_subject' => $post_subject,
    'post_message' => $post_message,
    'poster_id' => $this->session->userdata['id'],
    'topic_id' => $topic_id

Great thanks for cleaning it up Smile. Is there any way for me to remember the topic_id inserted in the sb_topics table?

[eluser]Armchair Samurai[/eluser]
the insert_id() function retrieves the last insert ID number, so you'd just call it again after the second insert.

How can the insert ID number help me remember what the topic_id number was (generated as an auto_increment value in the sb_topics table). I apologize for being such a noob Sad

[eluser]Armchair Samurai[/eluser]
The insert_id() function will retrieve the inserted ID from your insert query. So, for example, if your primary key in the sb_topics table is id, insert_id() will grab the new ID. Ergo, if you perform your query and the auto-incremented primary key field is 5, insert_id() will return 5.

HOLY @#*[email protected](#*[email protected]#!!!!!! It worked :-D, your my hero man. Ok so this insert_id still is like some sort of black magic to me though. So to clear it up, does insert_id() retrieve the primary key?

[eluser]Armchair Samurai[/eluser]
In a nutshell, yes, as long as it's a single field. I have no idea what would result if you tried with a multicolumn PK. Undoubtedly something involving a rip in the space-time continuum.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.