Welcome Guest, Not a member yet? Register   Sign In
Check if value exists in database?
#1

[eluser]invision[/eluser]
Hi,

I have a very simple model for adding users to my database.

Code:
function userExists() {    
        $email = $this->input->post('email');        
        $this->db->where("email",$email);
        $Q = $this->db->get('users');
        if ($Q->num_rows() > 0){
            return TRUE;
        }
    }

I run this in my Controller with:

Code:
if ($this->MUsers->userExists() == TRUE)
{
    die('bla - exists');
}

Now I wonder, how do I send the message back to my form page and still keep the form elements in place?

I basically just want to add a warning message above my form explaining the email is taken.



Many thanks for any help.
#2

[eluser]cahva[/eluser]
If you are using form validation, that is quite easy to achieve. Check the userguide about callbacks where you can define your own rules(and create userexists callback).
#3

[eluser]invision[/eluser]
Thanks for the reply cahva Smile

Here's my bit in the Controller:
Code:
function username_check()
    {
    
        if ($this->MUsers->userExists() == FALSE)
        {
            $this->form_validation->set_message('username_check', 'This email address has already been taken.');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }

....

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

and my Model excerpt:

Code:
function userExists() {    
        $email = $this->input->post('email');        
        $this->db->where("email",$email);
        $Q = $this->db->get('users');
        if ($Q->num_rows() > 0){
            return TRUE;
        }
    }

Is it something like this I should be aiming for?
#4

[eluser]cahva[/eluser]
Almost! Just remember to add callback_username_check to set_rules instead of plain username_check so that validation knows its your own rule.
#5

[eluser]invision[/eluser]
Hey,

Thanks again for the help.

I'm now using: callback_username_check

But it doesn't seem to be flagging it up, even though I know that email is taken.


Is this part of the Controller correct?
I've got my doubts.

Code:
if ($this->MUsers->userExists() == FALSE)


Thanks again
#6

[eluser]invision[/eluser]
Aaaah. It is Big Grin

I tried if ($this->MUsers->userExists() == TRUE)

and it now works beautifully.


Many thanks for your patience with me cahva. Have a great weekend Smile




Theme © iAndrew 2016 - Forum software by © MyBB