php - 如何查询 mySQL 数据库的一个属性并将结果与​​表单变量进行比较?

标签 php mysql forms codeigniter

在我的控制页面中,我需要在我的 users6 表中查询所有用户名条目,并与我的 View 页面上的表单中的 $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);
    }

最佳答案

这样做

$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;

FYI: It's better to use Model do DB queries.

关于php - 如何查询 mySQL 数据库的一个属性并将结果与​​表单变量进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49228475/

相关文章:

javascript - 通过单击灯箱中的单选按钮将内容添加到 tinymce

php - 在亚马逊aws中获得拒绝的权限

php - mysqli - 无法添加或更新子行 - 外键约束失败

mysql - 连接表和使用子查询时出现未知列

html - 即使正确设置了 tabindex,提交按钮也没有聚焦

ruby-on-rails - 同时将多个项目添加到购物车

javascript - PHP/JavaScript : See if someone is visiting the same url

javascript - 单击不同的按钮时如何更改 div 内容.javascript php html

MySQL 列从 UTF-8 迁移到 ASCII : Foreign Key and Unique Key constraints

css - simple_form_for rails 内联单选按钮