下面的代码有什么问题吗?请帮帮我。
我想将数据库中的管理员 ID 和密码与普通用户的登录 ID 和密码进行匹配,并进一步希望将控制权转移到相应的表单。
当我运行此代码时,它会出现以下错误:
Notice: Undefined variable: userstatus in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 25
Notice: Undefined variable: usertype in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 30
$query1="select user_type,user_staus from `user_info` where name='$username' and
password='$password'";
$fetched=mysql_query($query1);
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
if($userstatus==1) //if is logged in already
{
echo "Please login after some time";
exit();
}
if($usertype == 0) // if user is not an admin
{
$query1="select * from `user_info` where name='$username' and password='$password'";
$result = mysql_query($query1);
if(mysql_num_rows($result) == 1)
{
header("Location: user_form.php");
}
}
else if($usertype == 1) //if the user is a normal user
{
header("Location: admin_form.php");
}
else
{
echo "please register to login";
}
谁能帮我找出问题所在吗?
最佳答案
您的代码存在很多问题,您收到错误的主要原因是 $usertype
和 $userstatus
未预定义且未验证。
但在我看来,这不是您的代码的主要问题。
我想问你几个问题:
- 如果需要获取单行,为什么要创建两个循环?
- 如果您已经知道答案,为什么还要查询数据库两次?
- 您是否使用
mysql_real_escape_string
转义$username
和$password
中的不良字符方法?
以下是此代码的示例:
$query1 = "SELECT user_type,user_staus FROM `user_info` WHERE name='{$username}' AND password='{$password}' LIMIT 1";
$fetched = mysql_query($query1);
//check if record exists otherwise you would receive another notice that can
//break redirect functionality
if (mysql_num_rows($fetched))
{
$record = mysql_fetch_assoc($fetched);
// make sure that value is integer
if ((int)$record["user_staus"])
{
exit("Please login after some time");
}
else
{
$url = (bool)$record["user_type"] ? 'admin_form.php' : 'user_form.php';
header("Location: {$url}");
exit(0);
}
}
else
{
echo "please register to login";
}
更新
正如 nikc.org 建议的,删除了第三级 if
嵌套并替换为三元比较
关于php - 我的 PHP 脚本中出现 undefined variable 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830505/