Frank_g Frank_g - 15 days ago 5
PHP Question

How to prevent duplicate records in CodeIgniter

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

friends model:

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;
}


view:

<?php foreach($friends['following'] as $name):?>
<li> <?=anchor("profile/view/$name", $name)?>, (<?=anchor("home/drop/$name", 'drop')?>)</li>
<?php endforeach?>=


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?

Answer

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
    }
 }

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;
}

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

Comments