如何在单行中的多个表中运行多个查询

时间:2016-03-01 10:17:49

标签: php mysql

我在数据库中有两个不同的表:(1)userreg(2)admin。我想运行一个查询,首先检查userreg表,然后在admin表中。如果在userreg表中找到用户,那么如果用户在admin表中找到,则它将重定向到index.php页面,然后用户将重定向到admin.php页面。任何人都可以帮我这样做吗?

 $result = $conn->query("select * from userreg where email='$email' AND password = '$password'")||query("select * from admin where email='$email' AND password = '$password'");
    $row = $result->fetch_array(MYSQLI_BOTH);
    if($row)
    {
      /// session_start();
      $_SESSION["fullname"] = $row['fullname'];
      $_SESSION["email"] = $email;
      $_SESSION["cellno"]= $row['cellno'];
      $_SESSION["gender"]=$row['gender'];
      $_SESSION["uid"]=$row['uid'];
      $_SESSION['logged_in'] = true;
      //header('Location: index.php');
      $URL="./index.php";
        echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';

    }

1 个答案:

答案 0 :(得分:0)

处理此问题的最简单方法是在您的usertable中使用一个标志,允许注册用户被标记为管理员。但是,假设您无法修改表,则此代码应该有所帮助。

您可以将其用作返回所需数据的单个查询

IF (SELECT Count(*) FROM userreg WHERE email='$email' AND password='$password') = 1

    THEN
        SELECT *,1 as 'flag' FROM userreg where email='$email' AND password='$password'
ELSEIF (SELECT Count(*) FROM userreg WHERE email='$email' AND password='$password') = 0
    THEN
        IF (SELECT Count(*) FROM admin WHERE email='$email' AND password='$password') = 1
            THEN
                SELECT *,2 as 'flag' FROM admin where email='$email' AND password='$password'
        ENDIF
ELSE SELECT 0
ENDIF

然后对你的php代码进行一些小修改

 $result = $conn->query(); 
    $row = $result->fetch_array(MYSQLI_BOTH);
    if($row)
    {
      if ($row['flag'] = 0)
      {
        ///echo an error
      }
      else
      {
        /// session_start();
          $_SESSION["fullname"] = $row['fullname'];
          $_SESSION["email"] = $email;
          $_SESSION["cellno"]= $row['cellno'];
          $_SESSION["gender"]=$row['gender'];
          $_SESSION["uid"]=$row['uid'];
          $_SESSION['logged_in'] = true;
          //header('Location: index.php');
          if ($row['flag'] = 2)
          {
              $URL="./admin.php";              

          }
          else
          {
              $URL="./index.php";
          }
          echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';

    }

您需要充分意识到这不能防止SQL注入攻击。您需要参数化查询 - 有关如何执行此操作的信息,请参阅此SO帖子How can I prevent SQL injection in PHP?

参考:MySQL Docs