PHP Login form
Posted November 7th 2013, 4:18pm
Hello, hope this is the right section, if not then move it :D
Well, I have a little problem with a login form, I'm trying to check of the username and password from the database match the data that is inserted into the login form, if not it will return an error else it would log me into another page. here is my code:
$errors = array();

if (isset($_POST['username'], $_POST['password'])){
if (empty($_POST['username'])){
$errors[] = 'You must enter a username.';

if (empty($_POST['password'])){
$errors[] = 'You must enter a password.';

// Checks if the given username and password combination is vaild.
else {
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$password = $_POST['password'];
$passwordmd5 = md5($password);

$query = 'SELECT * FROM users WHERE user_name = "' . $username . '" AND user_password = "' . $password . '" LIMIT 1';
$result = mysql_query($query);
if( $result['user_name'] == $username && $result['user_password'] == $password ){
$username = mysql_fetch_assoc($result);
$query = 'UPDATE users SET session_id = "' . session_id() . '" WHERE user_name = ' . $username . ' LIMIT 1';
$_SESSION['username'] = htmlentities($_POST['username']);
header('Location: index.php');
} else if (($_POST['username'] && $_POST['password'])){
$errors[] = "Login/password combination not found.";

The problem is, that the code return the error 'Login/password combination not found.' even if the data is correct, so tell me whats wrong, I'm new with PHP so be sweet with me :D

Thanks in advance.
Best regards
Posts: 19
Joined: November 3rd 2013, 10:11am
Likes Given: 3
PHP Login form
Posted November 7th 2013, 8:54pm
I honestly don't know how that code even works, much less displaying an error message! There is a missing end-brace before the else clause here:

// Checks if the given username and password combination is vaild.
else {

Also, you are attempting to read queried data from a result pointer. You need something like:

$result = mysql_query($query);  
$data = mysql_fetch_assoc($result);

to access the data, in your case $data['user_name'] and $data['user_password'].

It's not necessary, but it would be a good idea to not use the mysql extension for database access; use mysqli instead. The mysql extension was deprecated in PHP5.5 and will be removed in PHP6.
Posts: 1599
Joined: March 12th 2009, 11:00pm
Location: Uncertain due to momentum
Likes Given: 26
Likes Received: 357

Who is online

Users browsing this forum: No registered users and 1 guest