I have records within the database for different account usernames and passwords. The database name is "admin" and the table name is "users". I feel like I have everything required to tell me whether the user has successfully logged in or not but it doesn't seem to work. One of the accounts within that database has the username "test" and the password "test". Even when I type in a correct account it still fails. Is there anything I'm missing or not noticing?
login.php page:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<h1>Login Page</h1>
<form action="confirm.php" method="POST">
<p>
<label>Username:</label>
<input type="text" id="user" name="user"/>
</p>
<p>
<label>Password:</label>
<input type="password" id="pass" name="pass"/>
</p>
<p>
<input type="submit" id="btn" value="Login"/>
</p>
</form>
</body>
</html>
confirm.php page:
<?php
//Get values passed in from form in login.php file
$username = $_POST['user'];
$password = $_POST['pass'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($username);
$password = mysqli_real_escape_string($password);
$conn = new mysqli("localhost", "root", "root", "admin");
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') ' . $conn- >connect_error);
}
$result = $conn->query("SELECT * FROM users where username = '$username' and password = '$password'")
or die ("Failed to query database " .$conn->error);
if ($row = $result->fetch_array()) {
echo "login success!!! Welcome " .$row['username'];
}
else {
echo "Failed to login!";
}
?>
Your problem is that you're not saving the connection returned from mysqli_connect
and using that in your subsequent calls to mysqli functions. Using the OOP form of these functions makes it a lot more obvious. Try something like this:
$conn = new mysqli("localhost", "root", "", "admin");
if ($conn->connect_error) {
die('Connect Error (' . $conn->connect_errno . ') ' . $conn->connect_error);
}
$result = $conn->query("SELECT * FROM users where username = '$username' and password = '$password'")
or die ("Failed to query database " .$conn->error);
if ($row = $result->fetch_array()) {
echo "login success!!! Welcome " .$row['username'];
}
else {
echo "Failed to login!";
}
Your next issue will be that you are vulnerable to SQL injection. To avoid that, you will need to use prepared statements. This question has a really good explanation of how to do that, and you can also look at the PHP manual page for MySQLi prepared statements here.