CodeIgniter Active Record:防止插入时出现重复

时间:2012-06-25 21:32:01

标签: codeigniter activerecord

我正在尝试使用SQLLite中的简单用户表来编写CodeIgniter,其中包含id,name,email。

如何在使用Active Record时阻止插入重复项?

我尝试了以下内容,但它只是不断创建重复...

$data = array(
  'email' => 'd@d.com' ,
  'name' => 'dave' 
);

$this->db->where('users.email != ', 'd@d.com');
$this->db->insert('users', $data); 

1 个答案:

答案 0 :(得分:0)

如上所述添加UNIQUE INDEX以确保完全安全。

然后你可以......做这样的事情:

$email = 'd@d.com';
$name = 'dave';

$this->db->query("
INSERT INTO users VALUES (email, name)
SELECT email, name
FROM (SELECT ? AS email, ? AS name) AS h
HAVING ! (SELECT COUNT(*) FROM users WHERE email = h.email)
", array($email, $name));