How to check if id already exists - codeigniter

前端 未结 7 1398
独厮守ぢ
独厮守ぢ 2021-02-09 06:56

i am trying to check if an id in the database already exists and if it does not then only insert that id and not the other ones that exist

I have tried to do a where sta

7条回答
  •  失恋的感觉
    2021-02-09 07:25

    normally 'id' field is set with auto_increment and set primary which is unique and not repeatable. So there is not problem to worry about existing.

    However, in your case I think you are not using it as a 'unique field'.

    Let me give you an example.

    Here I have a table name 'fruits'

    ++++++++++++++++++++++++++++++++++++
    ငfruit_id  | int (primary)
    name      | text 
    id        |  int
    ++++++++++++++++++++++++++++++++++++++
    

    in your model

    function checkId($id)
    {
       $query=$this->db->get_where('fruits',array('id'=>$id)); //check if 'id' field is existed or not
    
       if($query!=null)  // id found stop
       {
         return FALSE; 
       }
       else // id not found continue..
       {
           $data = array(
                 'fruit_id' => $fruit_id ,
                  'name' => $name ,
                 'id' => $id
            );    
          $this->db->insert('fruits', $data);          
       }    
    }
    

提交回复
热议问题