What would you expect to happen? Indeed if I look at the code so far it’s not doing anything, because no code is executed, unless you’ve not posted all your code?
Also, your code is wide open to SQL Injection. When using prepared statements, please do it properly:
$login = $conn->prepare("SELECT id, fname, lname, username, password FROM users WHERE username = ? AND password = ?");
$login->execute(array($user, $pass));
That way the query is first sent to the server, and then the variables are sent, so there can never be any confusion as to what belongs to the query and what belongs to the data, making SQL Injection impossible.
Besides, if you only need fname from the result, it would be better to SELECT only that field, and not add a bunch of other fields you don’t need
Are you remembering to call [fphp]session_start[/fphp] at the beginning of every page that needs access to the session?
There are a couple of other things I noticed about your code:-
You’re trying to use a prepared statement here, but you’re not getting the benefits of it because you’re including your values directly in the SQL string. What you need to do is use placeholders in the query, and then pass the values to the execute() method:
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(':username' => $username, ':password' => $password));
Doing this properly will protect your code against SQL injection attacks.
Thank you both for the very useful tips. I have adjusted the the code with your suggestions(I didn’t change the md5 hash as yet, but will do that later):
try
{
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
}
catch (PDOException $e)
{
echo 'Unable to connect to the database server.';
exit();
}
$sth = $conn->prepare("SELECT id, fname, lname, username, password FROM users WHERE username = ? AND password = ?");
$sth->execute(array($username, $password));
while ($row = $sth->fetch()) {
session_start();
$_SESSION['userName'] ="$row[username]";
header('Location: http://www.website.com/test2.php');
}
I have added session_start(); to test2.php. But still I am not redirected to test2.php.?
Please don’t do this. Even though it works (albeit with a E_NOTICE because ‘username’ is not quoted), it is very bad practice and I wouldn’t get in the habit of doing it this way if I were you. Instead, use