CodeIgniter - Checking to see if a value already exists in the database

后端 未结 7 1757
我在风中等你
我在风中等你 2020-12-24 13:25

Im running CodeIgniter for a project of mine ... Im fairly new to this, i have the standard form validation checks for my form, except im unsure of how to check if the value

7条回答
  •  爱一瞬间的悲伤
    2020-12-24 13:30

    If you want to make your validation function available in more than one controller, you should include the rule in a MY_Form_validation library.

    I do this in MY_Form_validation:

    function exist($str, $value){       
    
      list($table, $column) = explode('.', $value, 2);    
      $query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = $str'");
      $row = $query->row();
    
      return ($row->count > 0) ? FALSE : TRUE;
    
    }
    

    Then in your model (or controller) when you set your rules:

    $this->form_validation->set_rules('username','username','exist[users.user_name]');
    

    The rule calls the exist function.

    The exist function explodes the string users.user_name at the dot and then queries the database to see if a record is returned. If it does, return false, else true. The rule will fail on a false return.

提交回复
热议问题