php - 如何让我的 html/php 代码从 1 个提交按钮定向到两个不同的页面?
问题描述
我正在尝试使用 PHP 根据输入的用户名和密码组合定向到不同的表单:ssmith 转到 main_menu.php 和 tsmith 转到 menu.php。我已经尝试了所有我能想到的东西,但我在 Google 上找不到任何东西。有谁知道如何做到这一点?当我单击“登录”按钮时,无论我输入 ssmith 还是 tsmith,它总是转到 main_menu.php。这是我当前的代码:
<?php
//Connect to database
include "db_connect.php";
//Get variable from login form
$username=$_POST['username'];
$password=$_POST['password'];
//Check if any text has been entered in username and password
if ((empty($username)) || empty($password)){
echo "Please enter a username or password. Go back to the <a
href='Index.php'>login page</a>";
}
else {
//Check to see if username and password is found in table
$sql="SELECT * FROM accounts WHERE Username='ssmith'";
//Place the result of the sql query into the variable $result
$result=$mysqli->query($sql);
if($result=ssmith){
//Display main menu page
header("location:main_menu.php");
}
else {
//Check to see if username and password is found in table
$sql="SELECT * FROM accounts WHERE Username='tsmith'";
//Place the result of the sql query into the variable $result
$result=$mysqli->query($sql);
if($result=tsmith){
//Display menu page
header("location:menu.php");
}
else {
//Display error message
echo "Please username and password could not be found. Go back to the <a
href='Index.php'>login page</a>";
}
}
}
?>
解决方案
首先检查用户名中的U字母。它与您在数据库中使用的名称相同吗?否则使用以下代码
//first search anything from accounts
$sql="SELECT * FROM accounts";
//then navigate header according to the result
$result_query=$mysqli->query($sql);
if (mysqli_num_rows($result_query) > 0){
while($result = mysqli_fetch_assoc($result_query)){
if($result['username'] == 'ssmith'){
header("location:main_menu.php");
}elseif($result['username'] == 'tsmith'){
header("location:menu.php");
}
}
}