我创建了一个包含 MySQL 的登录页面。如果用户输入了正确的信息,它将把他们带到另一个页面,但是,如果他们没有输入正确的信息,那么页面应该刷新,并在顶部显示错误。目前,我的代码正在刷新页面顶部有错误但没有论坛登录。我不知道它有什么问题......
<?php
define("HOST", "localhost"); // The host you want to connect to.
define("USER", "root"); // The database username.
define("PASSWORD", "root"); // The database password.
define("DATABASE", "dfa24"); // The database name.
session_start();
if($_SERVER['REQUEST_METHOD'] === 'POST'){
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE)
or die("Failed to connect");
if(isset($_POST['submit'])) {
date_default_timezone_set('America/Phoenix');
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$sql = "SELECT * FROM Member WHERE loginName = '".$username."' AND password ='".$password. "'"; //checks for user in database
$result = $mysqli->query($sql) or die($mysqli->error); //shoots an error if something is wrong
if($result->num_rows < 1) // if the username/password is incorrect then an error message appears
{
echo "Invalid username/password combination. Please try again.";
$_SESSION['logged'] = '0';
}
else
{
$_SESSION['logged']='1';
$sql = " INSERT INTO Login (loginName,loginTime, loggedIn)
VALUES ('$username', NOW(), '1' ) "; // creates the login time.
$result = $mysqli->query($sql) or die ($mysqli->error); // shoots an error if i did something wrong.
$_SESSION['logname'] = $userlogin;
header("Location: MemberHomeScreen.php");
exit();
}
} else{
$x = false;
$defaults = array("username" => "", "password" => "");
$errors = array();
if(isset($_POST['submit'])) // Checks that the submit button has been pressed.
{
$x = true;
if(!isset($_POST['password']) || $_POST['password'] === '') // Checks to make sure there is a message in the message box.
{
$x = false;
array_push($errors, "** Please enter a password **");//Pushes an error
} else {
$defaults['password'] = $_POST['password']; //stores the item, so we do not lose it if there is an error.
}
if(!isset($_POST['username']) || $_POST['username'] === '') // Checks to make sure there is a message in the message box.
{
$x = false;
array_push($errors, "** Please enter a username **");//Pushes an error
} else {
$defaults['username'] = $_POST['username']; //stores the item, so we do not lose it if there is an error.
}
}
}
}
?>
<html>
<head>
<title> Member's Only Page </title>
</head>
<body>
<?php
echo "<h1> Please Sign In </h1>";
$userloginstuff = array("username" => "Username: ", "password" => "Password: ");
if($x === false){
foreach($errors as $error){ // goes through my errors and echos them in HTML.
echo "<div class='error'> $error </div>";
}
echo '<form action="" method="post">';
foreach ($userloginstuff as $name => $label){
echo "<div class = 'field'>",
"<label for='$name'>$label</label>";
echo "<input type='text' name='$name' id='$name' value=' '>";
}
echo "<input type='submit' name='submit'>";
}
echo"<br>";
echo "Don't have a username? <a href='Registration.php'> Click here.</a>"
?>
</body>
</html>