donglu5000 2015-03-22 03:16
浏览 96

如何在选择查询中获取2个表中的列值?

So I have 2 tables named tbl_admin and tbl_users. Each of them has a column named acct_type. All acct_type values in tbl_admin is 1 and in tbl_users, 0. I know it would be easy for me if I have just created one table for them. My question is, how can I query this so that I can redirect the admin to its page and the users to its page.

Here is my code

$uname = $_POST['txt_un'];
$pword = sha1($_POST['txt_pw']);

$query = "SELECT * FROM tbl_admin WHERE uname=? AND pword=?";


$stmt = $dbc->prepare($query);
$stmt->bindParam(1, $uname);
$stmt->bindParam(2, $pword);
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);

if ($row > 0) {
    if ($row['acct_type'] == 1) {
        header("Location: adminpage.php");
    } elseif ($row['acct_type'] == 0) {
        header("Location: userspage.php");
    }
} else {
    echo "<script>alert('Incorrect username/password');location.href='../index.php'</script>";
}

I know it will not work since I am only querying select from tbl_admin. Your help would be very much appreciated, thank you!

  • 写回答

2条回答 默认 最新

  • dongpei3245 2015-03-22 03:38
    关注

    assuming that your table (tbl_admin,tbl_users) have the same number of columns and each user entry in these two tables are unique. "you will have some serious problems in the future if not."

    $uname = $_POST['txt_un'];
    $pword = sha1($_POST['txt_pw']);
    
    $query = "SELECT * FROM tbl_admin WHERE uname=? AND pword=? UNION SELECT * FROM tbl_users WHERE uname=? AND pword=?";
    
    
    $stmt = $dbc->prepare($query);
    $stmt->bindParam(1, $uname);
    $stmt->bindParam(2, $pword);
    $stmt->bindParam(3, $uname);
    $stmt->bindParam(4, $pword);
    $stmt->execute();
    
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($row > 0) {
    if ($row['acct_type'] == 1) {
        header("Location: adminpage.php");
    } elseif ($row['acct_type'] == 0) {
        header("Location: userspage.php");
    }
    } else {
    echo "<script>alert('Incorrect username/password');location.href='../index.php'</script>";
    }
    

    For additional info regarding UNION, please check: http://dev.mysql.com/doc/refman/5.0/en/union.html

    Edit: as Half Crazed suggested, this approach should only be done if each user is unique in both tables. If you have additional time, you should revise the way you fetch your users

    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c