Php 从另一个表分配ID
在我的数据库中,我有3个表 笑话:Php 从另一个表分配ID,php,codeigniter,Php,Codeigniter,在我的数据库中,我有3个表 笑话: 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_TIMES
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 ;
类别:
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 ;
最后,评论:
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函数分配值并发送到模型:
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);
}
}
下面的model函数从html中获取数据,并将其放置在一个数组中
//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);
}
}
我的问题是,如何将笑话id的赋值更改为实际笑话id,以便为该标识符唯一存储该笑话的注释。目前,出于测试目的,它是1,因为我无法通过它的赋值。大多数SQL数据库在插入新行时会自动增加ID,因此不需要自己做。但如果需要,只需检索表中的最后一条记录并将ID设置为+1。在笑话视图中,您可以将笑话ID存储为隐藏的输入帖子,或存储在表单操作字段MYURL/insertComment?笑话ID=X get中的URI中 或存储在会话变量中
在controller now中,您可以将id传递给comments\u m->insertComment$joke\u id、$name、$comment 您必须传递参数id,在表单中使用隐藏字段。如果存在自动增量偏移怎么办?那么并发性呢?您永远无法通过添加+1来猜测自动增量的结果。即使没有自动增量偏移,也不会。这很糟糕,最糟糕的是-完全不可靠,而且不准确。如果您坚持一个模式,并且从不更改它,那么添加一个模式应该总是会产生一个新的唯一ID,而不管偏移量是多少,因为您通过添加1间接地将偏移量设置为1。至于并发性,这是另一回事,即使使用完全自动化的IDSOH,也要考虑和记住一些事情!另一个想法。如果使用纯sql注入来检索ID,那么并发性就会出现问题。但是使用过程调用将自动锁定表,直到插入新记录,从而防止添加重复的ID。这样,他只能向程序发送信息,程序将生成ID并进行插入。如果不想听起来粗鲁,你所写的一切都不是真的。该过程不会锁定表。将启动一个事务。这和锁不同。即使偏移量为1,事务也可能失败,并且自动生成的数字之间可能存在间隙。使用mysql以外的任何东西来控制ID生成都是错误的。