简体   繁体   中英

codeigniter Check if data exist in database update table row

How to check if a column exists in query builder Codeigniter 3? my database table name is "tags" and this table have two column (post_id and tag) here is my code to add tags to post:

//add post tags
public function add_post_tags($post_id)
{
    //tags
    $tags = trim($this->input->post('tags', true));

    $tags_array = explode(",", $tags);
    if (!empty($tags_array)) {
        foreach ($tags_array as $tag) {
            $tag = trim($tag);
            if (strlen($tag) > 1) {
                $data = array(
                    'post_id' => $post_id,
                    'tag' => trim($tag),
                    'tag_slug' => str_slug(trim($tag))
                );

                if (empty($data["tag_slug"]) || $data["tag_slug"] == "-") {
                    $data["tag_slug"] = "tag-" . uniqid();
                }

                //insert tag
                $this->db->insert('tags', $data);
            }
        }
    }
}

I want to check if data exists in the database update the post_id column if not exist insert new data "post_id" column like "5,8,9" I want to add the post number to the previous numbers when I update "post_id" column for example after update "post_id" column This table is like this "5,8,9,11" here 11 is my last post id

Try using replace() instead :

$this->db->replace('tags', $data);

Basically it inserts a new record if it doesn't exist, it updates it according to its primary or unique key if it does exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM