【问题标题】:How to query one attribute of mySQL database and compare results to a form variable?如何查询 mySQL 数据库的一个属性并将结果与​​表单变量进行比较?
【发布时间】:2018-08-20 01:47:10
【问题描述】:

在我的控制页面中,我需要在我的 usersas6 表中查询所有用户名条目,并与我的视图页面上的表单中的 $username 进行比较。其余的代码都很好。我已经尝试过了,但我似乎没有向 $myerror 变量添加任何内容,即使表中已经有一个带有表单用户名的条目。

  public function addPerson()
    {
      // GET AND SET POSTED DATA
      $username = $this->input->post('username');
      $password = $this->input->post('password');
      $accesslevel = $this->input->post('accesslevel');

      $myerror = "";
      // add the person to database with

        if (strlen($username) < 1)
        {
          $myerror = "The Username field is required.";
        }

        $query = $this->db->query("SELECT username FROM usersas6");
          foreach ($query->result() as $entry)
          {
              if ($username == $entry){
                $myerror .= "The Username is taken.";
              }
          }

        if(strlen($myerror) != 0){
          $this->TPL["myError"] = $myerror;
        }
        $this->getAllPerson();
        $this->template->show('Admin', $this->TPL);
    }

【问题讨论】:

  • 为什么不使用 where 子句并检查是否有返回行而不是循环所有记录?

标签: php mysql forms codeigniter


【解决方案1】:

试试这个检查数据库中的用户名

在你的模型中

public function function_name($username){
return $this->db->get_where('username', $username)->row()->username;
}

在你的控制器中

$this->load->model('model_name')l
$query = $this->model_name->function_name($username);
if($query)
{
    //Coding...
}

【讨论】:

    【解决方案2】:

    这样做

    $myerror = array();
    // add the person to database with
    
    if (empty($username))
    {
        $myerror[] = "The Username field is required.";
    }
    else
    {
        $query = $this->db->query("SELECT username FROM usersas6 WHERE username = '$username' "); # search for specific Username
        $result = $query->num_rows(); # count rows 
    
        if (!empty($result)) # or  if ($result > 0) 
        {
            $myerror[] = "The Username is taken.";
        }   
    }
    
    $this->TPL["myError"] = $myerror;
    

    仅供参考:最好使用模型进行数据库查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-16
      • 2019-12-19
      • 2012-10-27
      相关资源
      最近更新 更多