I’m writing a script (mostly for learning purposes) for logging into a database, using two different mySQL DB’s. Everything works, except some of the error catching. I have the following situations (the bold ones aren’t working):
- Blank username AND password
- Blank username
- Blank password
- Both username AND password contain data, but the username is wrong.
- Both username AND password contain data, but the password is wrong.
- Both username AND password contain data, and are correct.
Questions: Am I going about this efficiently, and why are (4) and (5) returning blank.
<?php
$loginstatus;
if(!$_POST["username"] && !$_POST["password"]){ //FROM HERE
$loginstatus = "You must enter a username & password!";
}elseif(!$_POST["username"]){
$loginstatus = "You must enter a username!";
}elseif(!$_POST["password"]){
$loginstatus = "You must enter a password!";//TO HERE WORKS
}elseif($_POST["username"] && $_POST["password"]){
require_once('config.php'); //contains db info
$db1 = mysql_connect($dbserver, $dbuser, $dbpass);
$db2 = mysql_connect($dbserver, $dbuser2, $dbpass2, true);
if ($db1 && $db2) { //both connections must have worked at the same time
mysql_select_db("nitrousc_tclydb", $db1); //connect using $db1 link
$userid = $_POST["username"]; //assign $userid to POST username
$userid = mysql_query("SELECT id FROM users WHERE username='$userid'", $db1)or die("Invalid Password!"); //THIS RETUNRS BLANK!
$userid = mysql_fetch_array($userid); //reuse $userid again, assigning the returned array.
$userid = $userid['id']; //reuse $userid again - at this point we lose the returned array.
mysql_select_db("nitrousc_tclyprv", $db2); //switch databases, using $db2
$password = mysql_query("SELECT * FROM users WHERE id='$userid'", $db2) or die("Invalid Password!"); //THIS RETUNRS BLANK!
$password = mysql_fetch_array($password); //resuse $password
$password = $password['hashed_password']; //resuse, store final hashed in $password
if (crypt($_POST["password"], $password) == $password){ //check the returned POST password against the hash
$loginstatus = "Login for".$_POST['username']."succesful!"; //THIS WORKS
};
}
}
echo $loginstatus;
?>
mysql_querywill always return true, it will only return false when the query is wrong.What you need to check is:
ALSO stop reusing the same variable for everything, that could lead to confusion and errors.