Hi,
I am new to PHP and I am wondering why my login page lets anyone log in, no matter what username and password they put in. It’s not checking usernames and passwords in my database first before letting the user sign in…
Have I missed something in my code?
[php]<?php
$output = NULL;
//IF USER SUBMITS FORM
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) || empty($password)) {
$output = "Please do not leave any fields blank.";
} else {
//CONNECT TO DATABASE
$dbhost = "localhost";
$dbuser = "secret";
$dbpass = "secret";
$dbname = "zb4885_movieclub";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//test for any database connection errors
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ")"
);
}
$username = $conn->real_escape_string($username);
$password = $conn->real_escape_string($password);
$query = ("SELECT * FROM user WHERE Username = '$username' AND Password = '$password'")or die(mysql_error());
$result = mysqli_query($conn, $query);
///////////
//Query successful
if ($result) {
session_start();
$_SESSION['loggedin'] = TRUE;
$_SESSION['user'] = $username;
$output = "Welcome " . $_SESSION['user'] . "!" . "<br><br>" . " <a href='addMovieForm.php'>Tell us which movie you want to see </a>" . "or <a href='index.php'> Continue browsing the site</a>" . "<br><br>" . "<button><a href='logout.php'>Log Out</a></button>";
}
else{
//Query Failure
$output = “Wrong username or password. Please try again.”;
}
}
}
if(!isset($_SESSION['loggedin'])) {
//DISPLAY WELCOME GUEST/DISPLAY LOG IN FORM
echo "<p>Please log in to add your favourite movie to our database, or <a href='index.php'>continue browsing.</a><p />";
?>
<!DOCTYPE html>
<h2>Login</h2>
<form method="POST">
<p>Username: </p><input type = "text" name = "username" />
<p>Password: </p><input type = "password" name = "password" />
<br><br><br><br>
<input type = "submit" name = "submit" value = "Submit"/>
</form>
</html>
<?php
} else {
//DISPLAY WELCOME 'USERNAME'/DISPLAY LOG OUT BUTTON
}
echo $output;
?>
<!DOCTYPE html>
<head>
<style>button a{color:#000;}body{font-family:'Dosis', sans-serif;background-color:#D3D3D3;}</style>
</head>
</html>
[/php]