简体   繁体   中英

Assigning an ID from another table

In my database, I have 3 tables.

Jokes:

CREATE TABLE IF NOT EXISTS `jokes` (
  `joke_id` int(11) NOT NULL AUTO_INCREMENT,
  `joke` varchar(1024) NOT NULL,
  `category_id` int(11) NOT NULL,
  `vote` int(255) NOT NULL,
  `date_added` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`joke_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

Category:

CREATE TABLE IF NOT EXISTS `category` (
  `category_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(51) NOT NULL,
  PRIMARY KEY (`category_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

And finally, Comments:

CREATE TABLE IF NOT EXISTS `comments` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(40) NOT NULL,
  `comment` text NOT NULL,
  `joke_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

insertComment function assignes the values and sends to the model:

public function insertComment(){
    if($this->input->post('act') == 'add-com'){
    $name = $this->input->post('user-com');
    $comment = $this->input->post('user-com');


    $this->comments_m->insertComment($name, $comment);


    }
}

The model function below grabs the data from the html, and places it an array.

//inserts the comments
function insertComment (){

    extract($_POST);
    if($_POST['act'] == 'add-com'){
        $data = array(
            'user' => htmlentities($user),
            'comment' => htmlentities($comment),
            'id_post' => $id_post = "1",
            //need to assign the joke_id to this string to fecth comments from specific joke
            'joke_id' => "1"

        );

        if(strlen($data['user']) <= '1'){
            $data['user'] = 'Guest';
        }

        $this->db->insert('comments', $data);
    }
}

My Question is, what can I do to alter the joke_id's assignment value to the actual joke_id so the comment for that joke will be uniquely stored for that idenity. At the moment it is "1" for test purposes, and because i can't get past the assignment for it.

In your Joke view you can store the joke_id, as hidden input (post), or in URI in form action field "MYURL/insertComment?joke_id=X" (get) Or store in the session variable

In controller now you can pass the id to comments_m->insertComment($joke_id, $name, $comment);

Most SQL databases increment the ID automatically when inserting a new row, so there should not be a need to do it yourself. But if you need to, just retrieve the last record in the table and set the ID to +1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM