views:

43

answers:

3

Hi, I'm working on creating a callback function in codeigniter to see if a certain record exists in the database, and if it does it'd like it to return a failure.

In the controller the relevent code is:

function firstname_check($str)
{

  if($this->home_model->find_username($str)) return false;
  true;
}

Then in the model I check the database using the find_username() function.

function find_username($str)
 {
  if($this->db->get_where('MasterDB', array('firstname' => $str)))
   {
    return TRUE;
   }

    return FALSE;
   }

I've used the firstname_check function in testing and it works. I did something like

function firstname_check($str)
 {

   if($str == 'test') return false;
   true;
 }

And in that case it worked. Not really sure why my model function isn't doing what it should. And guidance would be appreciated.

A: 
  if($this->home_model->find_username($str)) return false;
  true;

Given that code snippet above, you are not returning it true. If that is your code and not a typo it should be:

  if($this->home_model->find_username($str)) return false;
    return true;

That should fix it, giving that you did not have a typo.

EDIT: You could also just do this since the function returns true/false there is no need for the if statement:

function firstname_check($str)
{
  return $this->home_model->find_username($str);
}
Brad F Jacobs
I've found that it's in the query using var_dump. There is a string which it should be finding, but it's not. So it's always returning false.
Trent
A: 

So the solution involved taking the query statement out of if statement, placing it into a var then counting the rows and if the rows was > 0, invalidate.

Although this is a more convoluted than I'd like.

Trent
A: 

I find your naming kind of confusing. Your model function is called 'find_username' but it searches for a first name. Your table name is called 'MasterDB'. This sounds more like a database name. Shouldn't it be called 'users' or something similar? I'd write it like this :

Model function :

function user_exists_with_firstname($firstname)
{
    $sql = 'select count(*) as user_count 
            from users 
            where firstname=?';
    $result = $this->db->query($sql, array($firstname))->result();
    return ((int) $result->user_count) > 0;
}

Validation callback function :

function firstname_check($firstname)
{
    return !$this->user_model->user_exists_with_firstname($firstname);
}
Stephen Curran