PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] Codeigniter doesn't let me update entry, because some fields must be unique

 March 04, 2022     codeigniter, codeigniter-form-helper, mysql, php     No comments   

Issue

So what I'm trying to do:

  1. Pull User data from database, including email address, username etc.

  2. Edit it

  3. Save it

But I want to keep username and email unique. And for this I'm setting validation rules like this:

$this->form_validation->set_rules('firstname', 'First Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('lastname', 'Last Name', 'required|min_length[2]|max_length[15]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
$this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[12]|is_unique[users.username]');
$this->form_validation->set_rules('password1', 'Password', 'required|matches[password2]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'required');
$this->form_validation->set_rules('group', 'User Group', 'required');

And as you can see I have is_unique[users.username] and is_unique[users.email] rules. But it doesn't let me update my entry using this rules.

So the question is, how can I update database entry, and keep those 2 fields unique(username and email)?


Solution

use the call back validation function

$this->form_validation->set_rules('email', 'Email', 'required|valid_email|callback_check_user_email');

function check_user_email($email) {        
    if($this->input->post('id'))
        $id = $this->input->post('id');
    else
        $id = '';
    $result = $this->user_model->check_unique_user_email($id, $email);
    if($result == 0)
        $response = true;
    else {
        $this->form_validation->set_message('check_user_email', 'Email must be unique');
        $response = false;
    }
    return $response;
}

in model

    function check_unique_user_email($id = '', $email) {
        $this->db->where('email', $email);
        if($id) {
            $this->db->where_not_in('id', $id);
        }
        return $this->db->get('user')->num_rows();
    }

use same for the user name....



Answered By - parth
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing