以下代码属于我的用户登录表单。但是,在用户名和密码匹配并且页面被重定向后,它会在[路径]中显示错误'用户名中的未定义索引'。
<?php
session_start();
require_once "dbreg.php";
$errormsg = array();
$errorcount = 0;
if (!empty($_POST)) {
if (empty($_POST['username'])) {
$errormsg[] = "Enter valid username";
$errorcount++;
}
if(empty($_POST['password'])) {
$errormsg[] = "Please enter password";
$errorcount++;
}
if(!empty($_POST['username'])) {
$userquery = mysql_query("SELECT * FROM regform WHERE username='".$_POST['username']."'");
$useroutput = mysql_fetch_assoc($userquery);
if (empty($useroutput)) {
$errormsg[] = "Invalid username or password";
$errorcount++;
}
else {
$queryoutput = mysql_query("SELECT * FROM regform WHERE username = '".$_POST['username']."' AND userpass = '".$_POST['password']."'");
$newoutput = mysql_fetch_assoc($queryoutput);
if (empty($newoutput)) {
$errormsg[] = "Please enter valid login and password";
$errorcount++;
}
else {
$_SESSION['uid'] = $newoutput['id'];
header("Location: http://localhost/classwork2/userprofile.php");
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Login form</title>
</head>
<body>
<h1>Login</h1>
<?php
if (!empty($errormsg)) {
for ($i=0; $i < count($errormsg) ; $i++) {
# code...
?>
<div style="color:red"><?php echo $errormsg[$i]; ?></div>
<?php
}
}
?>
<table border="1">
<form name="lognow" id="lognow" action="reglogin.php" method="post" enctype="multipart/form-data">
<tr>
<td>
<label>Username</label>
</td>
<td>
<input type="text" name="username" id="username">
</td>
</tr>
<tr>
<td>
<label>Password</label>
</td>
<td>
<input type="text" name="password" id="password">
</td>
</tr>
<tr>
<td>
<input type="submit" value="Login">
</td>
</tr>
</form>
</table>
<h3>Or</h3>
<h2>
<a href="reg1.php">Click Here</a> to Register.
</h2>
</body>
</html>
以下是userprofile.php页面的代码
<?php
session_start();
require_once "dbreg.php";
$sql = "SELECT firstname, lastname FROM regform WHERE username = '" . $_SESSION['username'] . "'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo "Hello, " . $row['firstname'] . $row['lastname'] ;
?>
如果有人可以指导我做错了什么,那将是善意的。此外,如果我将上述代码保留在if(!empty($_POST['username']))
内,则页面显示为空白。
答案 0 :(得分:0)
问题是,您在成功登录后从未进行/设置$_SESSION['username'] = "YOUR_USERNAME"
,您刚刚执行$_SESSION['uid'] = $newoutput['id'];
并将用户重定向到 userprofile.php 页面。
解决方案是,根据用户的id
构建您的查询,而不是用户的username
。在 userprofile.php 页面中,更改如下所示的查询:
$sql = "SELECT firstname, lastname FROM regform WHERE id = '" . $_SESSION['uid'] . "'";
// your code
Sidenote: mysql_*
函数自PHP 5.5起已弃用,并在PHP 7.0中完全删除。请改用mysqli
或pdo
。并且this is why you shouldn't use mysql_* functions。