【问题标题】:How to prevent duplicate records in CodeIgniter如何防止 CodeIgniter 中的重复记录
【发布时间】:2012-12-07 21:36:52
【问题描述】:

我会选择的人将在我的朋友数据库中出现两次。如何防止重复条目进入此处?我曾尝试使用存在 sql 命令但没有运气

朋友模型:

   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 语句中使用 exists 关键字?

【问题讨论】:

  • 使用CI的验证规则is_unique
  • "停止重复的条目进入我的数据库"...你是什么意思...我在你的问题中看不到插入查询或任何做条目的事情,,,
  • 您要做什么?防止数据库中出现重复条目​​或防止选择重复条目?

标签: php sql codeigniter phpmyadmin


【解决方案1】:

只需在插入前检查用户名/朋友名是否存在:

$q =  $this->db->select('username')
      ->from('friends')
      ->where(array('username' => $username, 'friend' => $friendname))->get();
if($q->num_rows() == 0){
    //insert goes here
}

【讨论】:

  • 我真的很想使用它,因为它看起来很容易理解,但后来我收到了关于我的 sql 语法的错误:错误号:1064 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的“id #32, Resource id #40, 0, 0, NULL)”附近使用正确的语法 INSERT INTO friends (conn_id, result_id , current_row, num_rows, row_data) 值(资源 ID #32,资源 ID #40, 0, 0, NULL)
  • 一个简单易懂的答案。非常适合我
【解决方案2】:

我认为您没有设置表以获得更好的性能。

CREATE TABLE friends (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
userId INT UNSIGNED NOT NULL,
friendId INT UNSIGNED NOT NULL,
FOREIGN KEY (userId)
    REFERENCES users(userId)
    ON UPDATE CASCADE ON DELETE CASCADE,
FOREIGN KEY (friendId)
    REFERENCES users(userId)
    ON UPDATE CASCADE ON DELETE CASCADE,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
ALTER TABLE friends ADD UNIQUE INDEX (userId, friendId);

这种通过 id 存储朋友的清晰简单的解决方案可以防止重复。 InnoDB 引擎维护您的数据完整性,并且当您从 users 表中删除某人时 - Friends 表中包含该用户的好友的所有行将被自动删除。

【讨论】:

  • 其他建议插入前检查的答案有一天会失败,除非这是一个微不足道的单用户数据库。防止重复的正确方法是在数据库级别而不是在应用程序逻辑中应用约束。 Pavel K 列出了唯一正确的方法。
【解决方案3】:

当您插入时,您可以调用您的 getFollowing 方法并像这样:

function add_follower($username, $friend_username)
{
    $current_followers = $this->getFollowing($username);

    if(!in_array($friend_username, $current_followers)
    {
        // Add to followers
    }
 }

为此,您需要将您的 getFollowing 更改为:

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% 正确,因为我不知道您的数据库/模型是如何配置的。但它应该让您大致了解如何执行此操作

【讨论】:

  • 这会从表中提取所有记录,只是为了检查一个用户名是否在结果数组中。我认为专门查询一个用户名的存在会更有效(请参阅下面的答案)。
【解决方案4】:

在插入新记录之前,您必须在数据库中进行检查,因为数据库中已经存在任何条目。下面是代码...

function addFriend($username, $friendname)
{
    $user_name = $this->getFollowing($username);

    if( empty($user_name) )
    {
         $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();

    if( !empty($followingSet) )
    {
         foreach ($followingSet->result() as $row)
         {
              $following[] = $row->friend;
         }
    }
    return $following;
 }

另外我希望您建议,在使用之前始终检查数组是否为空。就像你在 foreach 循环中使用它一样,循环会产生错误。

【讨论】:

  • 现在这确实有效,因为一旦我添加了一个要关注的人,就根本无法添加更多朋友 - 无论我是否已经关注他们,我现在都无法添加更多关注者
【解决方案5】:

在你想应用查询以读取某些内容的地方试试这个,在数据库查询中应用不同

   $this->db->distinct();

【讨论】:

    【解决方案6】:

    在你的模型中尝试这样的事情:

    /**
     * Return true if don't find row in DB.
     * @param array $ay_value
     * @param array $ay_column
     * @param string $table
     * @throws Exception
     * @return boolean
     */
    
    public function check_double_content($ay_value, $ay_column, $table) {
    
        if ((is_array($ay_value)) AND (is_array($ay_column))) {
    
            if (count($ay_value) == count($ay_column)) {
    
                foreach ($ay_column AS $key => $column) {
                    $this->db->where($column, $ay_value[$key]);
                }
    
                $this->db->from($table);
                $query = $this->db->get();
    
                if ($query->num_rows() > 0) {
                    return false;
                } else {
                    return true;
                }
    
    
    
            } else {
                throw new Exception("\$ay_value and \$ay_coulm must have same rows");
            }
    
        } else {
            throw new Exception("\$ay_value and \$ay_column must by array");
        }
    
    }
    

    【讨论】:

    • 请避免在没有明确说明他们如何回答问题的情况下发布代码转储作为答案。
    猜你喜欢
    • 1970-01-01
    • 2016-08-24
    • 2016-07-10
    • 2015-12-04
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多