检查用户是否为admin PHP

时间:2015-02-08 14:53:11

标签: php

我有一个具有这种结构的用户表:

ID
用户名
密码
经销商(管理员)

现在我想检查登录,如果用户是经销商,经销商可以保持值0(普通用户)或1(管理员),但我不知道如何做到这一点(我是新手PHP)。

这是登录表单:

    <form action="index.php?action=login" method="post" style="width: 50%;">
        <input type="hidden" name="login" value="true" />

<?php if ( isset( $results['errorMessage'] ) ) { ?>
        <div class="errorMessage"><?php echo $results['errorMessage'] ?></div>
<?php } ?>

        <ul>

          <li>
            <label for="username">Username</label>
            <input type="text" name="username" id="username" placeholder="Uw gebruikersnaam" required autofocus maxlength="20" />
          </li>

          <li>
            <label for="password">Password</label>
            <input type="password" name="password" id="password" placeholder="Uw wachtwoord" required maxlength="20" />
          </li>

        </ul>

        <div class="buttons">
          <input type="submit" name="login" value="Login" />
        </div>

      </form>

这是登录功能:

    function login() {

  $results = array();
  $results['pageTitle'] = "Admin Login | Gemeente Urk";

  $host = "localhost";
  $mysqluser = "root";
  $mysqlpass = "usbw";
  $db = "wagenpark";

  mysql_connect($host, $mysqluser, $mysqlpass);
  mysql_select_db($db);

  if ( isset( $_POST['login'] ) ) {

      $gebruiker = $_POST['username'];
      $wachtwoord = $_POST['password'];
      $sql = "SELECT * FROM users WHERE username='".$gebruiker."' AND password='".$wachtwoord."' LIMIT 1";
      $res = mysql_query($sql) or die (mysql_error());
      if (mysql_num_rows($res) == 1) {
          $_SESSION['username'] = $gebruiker;
          header( "Location: index.php" );

    } else {

      // Login failed: display an error message to the user
      $results['errorMessage'] = "Incorrect username or password. Please try again.";
      require( TEMPLATE_PATH . "/admin/loginForm.php" );
    }

  } else {

    // User has not posted the login form yet: display the form
    require( TEMPLATE_PATH . "/admin/loginForm.php" );
  }

}

谢谢。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,你有一个MySQL数据库,你可以在其中保存用户名,身份证,密码以及他/她是否为管理员。在这部分:

$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1) {
      $_SESSION['username'] = $gebruiker;
      header( "Location: index.php" );

您可以获取结果的Admin值。它可能看起来像这样:

$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) == 1) {
      $_SESSION['username'] = $gebruiker;
      while($row = mysql_fetch_object($res))
      {
          $admin = $row->Admin;
      }
      if ($admin == 1) {Do something...}
      else {Do something if he is not Admin}
      header( "Location: index.php" );

然后你可以将它保存到$ _SESSION。

我跳了帮助,如果它不起作用,请告诉我。