The other day I posted something on another forum and a person stated that the following was incorrect.
[php]function login_user(array $data, PDO $pdo) {
/*
* Setup the Query for reading in login data from database table
*/
$query = 'SELECT id, username, password, email FROM users WHERE username=:username';
try {
$stmt = $pdo->prepare($query); // Prepare the query:
$stmt->execute([':username' => $data['username']]); // Execute the query with the supplied user's parameter(s):
} catch (Exception $ex) {
die("Failed to run query: " . $ex->getMessage()); // Do Not Use in Production Website - Log error or email error to admin:
}
$stmt->setFetchMode(PDO::FETCH_OBJ); // Fetch the user's information as object(s):
$user = $stmt->fetch();
/*
* If username is in database table users then proceed to check password entered against stored password.
*/
if ($user) {
$loginStatus = password_verify($data['password'], $user->password); // Check the user's entry to the stored password:
unset($data['password'], $user->password); // Password(s) not needed then unset the password(s)!:
} else {
return FALSE;
}
/*
* If passwords word match then store user's information in sessions and return true from function.
*/
if ($loginStatus) {
$_SESSION['user'] = $user; // Set the session variable of user:
return TRUE;
} else {
return FALSE;
}
}[/php]
Specifically line 16, say that it might cause problems with other database formats (other than MySQL). The poster wasn’t too friendly and I thought a little full of himself. Needless to say I probably stick to PHPHelp to post those kind of threads from now on. Anyways, I went to my php books where I learned majority of my PHP and that is basically what they had. However, I did tighten up the code to the following:
[php]function login_user(array $data, PDO $pdo) {
/*
* Setup the Query for reading in login data from database table
*/
$query = "SELECT id, username, password, email, DATE_FORMAT(birthday, '%M %e, %Y') as birthday FROM users WHERE username=:username";
try {
$stmt = $pdo->prepare($query); // Prepare the query:
$stmt->execute([':username' => $data['username']]); // Execute the query with the supplied user's parameter(s):
} catch (Exception $ex) {
die("Failed to run query: " . $ex->getMessage()); // Do Not Use in Production Website - Log error or email error to admin:
}
$results = $stmt->fetch(PDO::FETCH_OBJ);
if (count($results) > 0 && password_verify($data['password'], $results->password)) {
unset($data['password'], $results->password);
$_SESSION['user'] =$results;
return (boolean) TRUE;
}
}[/php]
Anyways I think he’s wrong or incorrect, but I just want to be sure from someone else who might have experience in other databases other than MySQL.