0

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

  • what's the reason to store the `post_id` like that? why not normalize it? here is the problem list of storing comma-separated in a single column : [Is storing a delimited list in a database column really that bad?](https://stackoverflow.com/a/3653574/8566549) – Hasta Dhana Apr 06 '19 at 06:18

1 Answers1

0

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.

Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26