简体   繁体   English

带有sql + codeigniter的表单验证

[英]Form Validation w/ sql + codeigniter

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. 我正在努力在codeigniter中创建一个回调函数,以查看数据库中是否存在某个记录,如果这样做,则希望它返回失败。

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. 然后在模型中,我使用find_username()函数检查数据库。

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. 我在测试中使用了firstname_check函数,并且可以正常工作。 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. 指导将不胜感激。

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

Given that code snippet above, you are not returning it true. 鉴于以上代码段,您没有将其返回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: 编辑:您也可以只执行此操作,因为该函数返回true / false,因此不需要if语句:

function firstname_check($str)
{
  return $this->home_model->find_username($str);
}

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. 因此,解决方案包括将查询语句从if语句中取出,将其放入var中,然后对行进行计数,如果行> 0,则使该语句无效。

Although this is a more convoluted than I'd like. 尽管这比我想的要复杂。

I find your naming kind of confusing. 我觉得您的命名有点令人困惑。 Your model function is called 'find_username' but it searches for a first name. 您的模型函数称为“ find_username”,但它会搜索名字。 Your table name is called 'MasterDB'. 您的表名称称为“ 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM