Gavin Estaco Gavin Estaco - 3 months ago 18
MySQL Question

Simple PHP/MySQL Form Only Refreshes

I just followed a guide to set up a very simple login system with PHP and MySQL and my code is an exact clone from the video but when I hit the submit button it just refreshes my page no matter what values are in the username/password boxes. The guide was from 2010 but I assumed that it would work because the system is so simple.

XAMPP INFO:

table name is 'users'

database name is 'fast'

<?php

$host = "localhost";
$user = "root";
$pass = "";
$db = "fast";

mysql_connect($host, $user, $pass);
mysql_select_db($db);

if (isset ($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql);
if (mysqli_num_rows($res) == 1) {
echo "You have succesfully logged in.";
exit();
} else {
echo "Invalid login information. Please return the previous page";
exit();
}
}

?>



<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>

<body>
<form method="POST" action="login.php">
Username: <input type="text" name="username"></input>
Password: <input type="password" name="password"></input>
<input type="submit" name="submit" value="Log In"></input>
</form>
</body>
</html>

art art
Answer

EDITED VERSION

Make a separate connect.php file and include it in your login.php file also i have updated isset condition of in your login.php file.If submit button is clicked then the validation conditions work

(mysql is deprecated after PHP version 5.5 and use pdo or mysqli)

connect.php

<?php

$host = "localhost";
$user = "root";
$pass = "";
$db = "fast";

mysql_connect($host, $user, $pass);
mysql_select_db($db);
?>

login.php

 <?php
        require('connect.php');
        if (isset ($_POST['submit'])) {
            $username = $_POST['username'];
            $password = $_POST['password'];
        $sql = "SELECT * FROM users WHERE username='".$username."' AND     password='".$password."' LIMIT 1";
        $res = mysql_query($sql);
        if ($res) {
            echo "You have succesfully logged in.";
            exit();
        } else {
            echo "Invalid login information. Please return the previous page";
            exit();
        }
    }

    ?>
<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>

<body>
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
        Username: <input type="text" name="username"></input>
        Password: <input type="password" name="password"></input>
        <input type="submit" name="submit" value="Log In"></input>
    </form>
</body>
</html>
Comments