I'm building my first test site and I'm having a little trouble validating user login. I've google for solutions but my code looks correct and similar to those I've found online. I've created a test username and password in my database to test for validation. Even when I input a valid username and password in the form login, it doesn't recognize the user and redirect to a page where valid users should go. Any help is greatly appreciated.
Here is my form code:
Code: Select all
<form action="login.php" method="POST">
<table>
<tbody>
<tr><td>Username: </td> <td><input type="text" name="username" size="25"></td></tr>
<tr><td>Password: </td> <td><input type="password" name="password" size="25"></td></tr>
</tbody>
</table><br>
<input type="submit" value="Login">
</form>
Code: Select all
<?php
session_start();
if ( isset($_POST['username']) && isset($_POST['password']) )
{
$host = 'localhost'; // Host name
$username = 'root'; // Mysql username
$password = 'root'; // Mysql password
$db_name = 'practiceset'; // Database name
// Connect to server and select databse.
$db_conn = mysql_connect($host, $username, $password)
or die("Cannot connect to Database.");
mysql_select_db($db_name)
or die("Cannot select Database.");
// username and password sent from form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];
$mypassword = md5($mypassword);
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$result = mysql_query("SELECT *
FROM user
WHERE username='$myusername' AND password='$mypassword'");
// Mysql_num_row is counting table row
$count = mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1)
{
// Register $myusername, $mypassword and redirect to file "login_success.php"
$row = mysql_fetch_assoc($result);
$_SESSION['userid'] = $row['id'];
session_register('username');
session_register('password');
header('Location: generaljournal.php');
}
else
{
$_SESSION['login_error'] = '1';
$header = 'Location: ./';
header($header);
}
mysql_close($db_conn);
}
?>