Hi Developers,
I'm a beginner on php/mysql and I would like some help on my LOGIN FORM. I created a database called user, table called users, and I inserted two users with two passwords. The passwords have not been encrypted yet.
hen I run my login form, If I enter a diffrent username, it'll catch that it is an incorrect username but if I entered the two usernames in the DB, there are no errors. My main problem is when I enter the password or a random password, it takes me to a blank page. It doesn't produce the echo 'Login succesfful'. It just takes me to a blank page. I hope I didn't confuse anyone. Please assist me this problem. I've been on it for a while and am not able to figure it out. Thank you.
**my Database:**
------------
CREATE DATABASE user;
USER user;
CREATE TABLE users (
id int(4) NOT NULL AUTO_INCREMENT,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
PRIMARY KEY (id));
INSERT INTO users (username, password)
VALUES ('john', 'johndoe');
INSERT INTO users (username, password)
VALUES ('bill', 'clinton');
**form.php**
----------
<body>
<form name="login" method="post" action="login.php">
<b>Username: </b>
<input type="text" name="username" />
</br>
<b>Password: </b>
<input type="password" name="password" />
</br>
<input type="submit" name="submit" value="Log in"/>
</form>
</body>
</html>
**db_connect.php**
--------------
<?php
$username = "root";
$password = "";
try {
$pdo = new PDO('mysql:dbname=user;host=localhost',$username, $password);
} catch (PDOException $e) {
die('ERROR: Could not connect: ' . $e->getMessage());
}
//Better to use PDO connection because you can easily transfer it to another DB compared to mysqli and mysql
?>
**login.php ** <--- my problem is in this file
---------
<?php
session_start();
include('db_connect.php');
if(!isset($_POST['submit']))
{
include('form.php');
}
else
{
$username = $_POST['username'];
$password = $_POST['password'];
//Check input
if($username == '')
{
die('ERROR: Please enter your username.');
}
if($password == '')
{
die('ERROR: Please enter your password.');
}
//Escapes special characters in a string
$username = mysql_real_escape_string($_POST['username']);
//Check if username exists
$sql = "SELECT COUNT(*) FROM users WHERE username ='$username'";
if($result = $pdo->query($sql))
{
$row = $result->fetch();
//if yes, fecth the encrypted password
if($row[0] == 1)
{
$sql = "SELECT password FROM users WHERE username ='$username'";
//encrypt the password entered into the form
//test it against the encrypted password store in DB
if($result = $pdo->query($sql))
{
$row = $result->fetch();
$salt = $row[0];
if(crypt($password, $salt) == $salt)
{
echo'Login credential successful';
}
else
{
echo'You entered an incorrect password.';
}
} else {
echo "Error: Could not execute $sql. " . print_r($pdo->errorInfo());
}
} else {
echo 'Incorrect username';
}
} else{
echo "Could not execute $sql. " . print_r($pdo->errorInfo());
}
//close connection
unset($pdo);
}
?>