mysql-如果不存在则插入Codeigniter

我的控制器:

function getFeed()
{
   $feed_url = $this->input->get("url");
   $content = file_get_contents($feed_url);
   $x = new SimpleXmlElement($content);

    foreach($x->channel->item as $entry) {
        $feeds[] = array(
                         'title' => (string)$entry->title,
                         'url'=> (string)$entry->link,
                         'username' => $this->session->userdata('username')                      
                );

        $this->load->model('membership_model');
        $this->membership_model->feeds($feeds);
    }

模型:

function feeds($feeds_data)
{   
        $this->db->insert_batch('feeds', $feeds_data);
}

如果表中仅不存在该行,是否有要插入的函数?我有一个包含4列的表格:id,title,url,username.当我单击他时,我有一个锚点,它调用geFeed函数并将信息插入表中.但是我只想插入如果不存在.

解决方法:

我也面临同样的挑战,因此我最终想出了一个可能对您有帮助的功能.

    function safe_update_batch($table_name,$records,$filter_field)
    {
        $filters=array();

        foreach($records as $record)$filters[]=$record[$filter_field];

        $this->db->query("SET SESSION group_concat_max_len=10000000");

        $query=$this->db->select("GROUP_CONCAT($filter_field) AS existing_keys",FALSE)->where_in($filter_field, $filters)->get($table_name);

        $row=$query->row();
        $found_fields=explode(',',$row->existing_keys);         

        $insert_batch=array();
        $update_batch=array();

        foreach($records as $record)
        {
            if(in_array($record[$filter_field],$found_fields))$update_batch[]=$record;
            else $insert_batch[]=$record;
        }

        if(!empty($insert_batch))$this->db->insert_batch($table_name,$insert_batch);
        if(!empty($update_batch))$this->db->update_batch($table_name,$update_batch,$filter_field);      
    }

//样本用法

$this->safe_update_batch('feeds', $feeds_data,'title');
上一篇:PHP-将变量从MY_Controller传递到视图


下一篇:php-CodeIgniter搜索结果分页