I hope you are all having a wonderful day so far. I have a question in regards to PHP and MYSQL Login page that I created. It seems to be not working. Thank you for the help in advance.
<?php
$db = mysqli_connect("localhost", "root", "", "test");
if (isset($_POST['login'])) {
$username = mysqli_real_escape_string($db,$_POST['username']);
$password = mysqli_real_escape_string($db,$_POST['password']);
$query = "SELECT * FROM users WHERE Username='$username' AND Password='$password'";
$result = mysqli_query($db,$query);
$count = mysqli_num_rows($result);
if($count == 1) {
session_register("username");
header('location: home.html');
}else {
echo "Your Login Name or Password is invalid. Please try again.";
} }?>
Advertisement
Answer
I am create simple login page using php pdo. and it is work successfully. so please you try this code
<?php
session_start();
//This is a database connection
$host_name = "localhost";
$user_name = 'root';
$db_name = "stackoverflow";
$pass = '';
$conn = new PDO("mysql:host=$host_name; dbname=$db_name;", $user_name, $pass);
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<!--- This is a login form ----->
<form method="post">
<input type="text" name="uname" placeholder="Username" required /><br><br>
<input type="password" name="upass" placeholder="Password" required /><br><br>
<button type="submit" name="login-submit" >Login</button>
</form>
</body>
</html>
<?php
if (isset($_POST['login-submit']))
{
$uname = $_POST['uname']; //This is a username
$pass = $_POST['upass']; //This is a password
$sql = "SELECT * FROM login WHERE username LIKE ? AND password LIKE ?"; // This is a sql check username and password in our database
$checkUsernameAndPassword = $conn->prepare($sql);
$checkUsernameAndPassword->execute([$uname, $pass]);
if ($checkUsernameAndPassword->rowCount() == 1) //check if the sql return row 1 then connction success otherwise i will show error.
{
$_SESSION['username'] = $uname;
header('location: index.php');
}
else
{
echo "<h3>Please enter the valid username or password</h3>";
}
}
?>