Welcome Guest, Not a member yet? Register   Sign In
Update email only if the email doesn't exist in the database
#1

I have an update page for my users where they can edit their name, email and other info.

So far, they can edit everything. Including their email. They can enter an email that already exists in the database without any issue.

I have tried adding this form validation rule

PHP Code:
$this->form_validation->set_rules('email''Email''trim|required|xss_clean|is_unique[users.email]'); 
But that doesn't help because it will ask the user to enter another email if they click the save button, even if they don't want to change their email.

I just want to make it so that when they click the save button, only update the email if the user has changed it AND check that the email doesn't exist in the database before saving.

I have tried doing this but no luck.

The code that I'm playing with:
PHP Code:
$first_name $this->input->post('first_name');
    
$last_name $this->input->post('last_name');
    
$email $this->input->post('email');
    
$uid $this->session->userdata('uid');

    
//$query = $this->db->get('dayone_entries');
    
$query $this->db->query('SELECT uid, email FROM users');


    
$sql "UPDATE users SET first_name = '{$first_name}', last_name = '{$last_name}', email = '{$email}' WHERE uid = $uid LIMIT 1";
    
$this->db->query($sql);

    if (
$this->db->affected_rows() === 1) {

        return 
true;
    } else {
        return 
false;
    } 
Reply
#2

(This post was last modified: 03-04-2015, 06:35 PM by silentium.)

Add a hidden form field named 'original_email' and set the value to the users email. This field will be used as reference to detect if the users has changed the email when saving.

In the form validation PHP code we only add the unique form validation if needed.

PHP Code:
// We do the unique check only if the email field to not match the original email
if ($this->input->post('email') != $this->input->post('original_email')) {
    
$this->form_validation->set_rules('email''Email''trim|required|xss_clean|is_unique[users.email]'); 

Reply




Theme © iAndrew 2016 - Forum software by © MyBB