如何防止CodeIgniter中的重复记录 [英] How to prevent duplicate records in CodeIgniter
问题描述
我会选择的人然后在我的朋友数据库中出现两次.如何防止重复的条目进入这里?我尝试使用存在的sql命令,但是没有运气
The person I would have selected will then appears as twice in my friends database. How do I prevent a duplicate entry going in here? I have tried using exists sql command but no luck
朋友模型:
function addFriend($username, $friendname)
{
$record = array('username'=> $username,
'friend' => $friendname);
$this->db->insert('friends', $record);
}
function getFollowing($username)
{
$following = array();
$this->db->select('*')->from('friends')->where('username', $username);
$followingSet = $this->db->get();
foreach ($followingSet->result() as $row)
{
if(isset($username)){
$following[] = $row->friend;
}
else
{
return false;
}
}
return $following;
}
视图:
<?php foreach($friends['following'] as $name):?>
<li> <?=anchor("profile/view/$name", $name)?>, (<?=anchor("home/drop/$name", 'drop')?>)</li>
<?php endforeach?>=
我想做的就是停止重复的条目进入数据库-我将如何在sql语句中使用exist关键字?
The thing I want to do is stop duplicate entries going in my database - how would I use the exists keyword in my sql statement?
推荐答案
插入时,您可以调用 getFollowing
方法并执行以下操作:
When you insert you can call your getFollowing
method and go like this:
function add_follower($username, $friend_username)
{
$current_followers = $this->getFollowing($username);
if(!in_array($friend_username, $current_followers)
{
// Add to followers
}
}
为此,您需要将 getFollowing
更改为此:
For this you need to change your getFollowing
to this:
function getFollowing($username)
{
$following = array();
$this->db->select('*')->from('friends')->where('username', $username);
$followingSet = $this->db->get();
foreach ($followingSet->result() as $row)
{
$following[] = $row->friend;
}
return $following;
}
这可能不会100%正确,因为我不知道如何配置您的数据库/模型.但这应该使您对如何执行此操作有一个大致的认识
This will not work 100% right probably, because I have no idea how your database / models are configured. But it should give you a general idea on how to do this
这篇关于如何防止CodeIgniter中的重复记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!