Search code examples
codeignitercodeigniter-url

Alert primary key insert


How to create a primary key alerts when the data input together with CodeIgniter? example if I insert 001 but in the database already exists 001 subsequently appeared alert


Solution

  • In your Model you can run an SQL query to see if the primary key is already present. If it is, then you can simply return an error code to the Controller, which should handle things from there (by sending an error message to the View).

    Model

    function checkPrimaryKey($primary_key){
        $sql = "SELECT * FROM table_name WHERE primary_key = '$primary_key'";
        /* Replace table_name And primary_key With Actual Table Name And Column Name */
        $query=$this->db->query($sql);
        if($query->num_rows() == 1){
            return -1; //Key already exists
        }
        else{
            return 0;  //Key does not exist
        }
    }
    

    Controller

    function checkPrimaryKey($primary_key){
        $this->load->model('Model_name');
        if($this->Model_name->checkPrimaryKey($primary_key)==-1){
            //Appropriate Error Message
        }
        else {
            //Call Some Model Function to Insert The Data And/Or Display Appropriate Success Message
        }
    }