Simple piece of PHP code:
#login.php
$_SESSION['valid_user_id'] = getUserId($username, $password);
#user_auth_fns.php
function getUserId($username, $password)
{
$username = addslashes($username);
$username = mysql_real_escape_string($username);
$password = addslashes($password);
$password = mysql_real_escape_string($password);
$conn = db_connect();
$result = $conn->query("select id from user where username='$username' and password= sha1('$password')");
if (!$result) {
throw new Exception('Could not retrieve your user id.');
}
if ($result->num_rows > 0) {
return $result;
} else {
throw new Exception('Could not retrieve your user id.');
}
}
“return $result” is wrong, however I have no idea what I should put there in order to return the id from a certain user. The PHP manual didn’t provide the answer either. I know this function works because replacing
return $result by return “test”
returns the correct value as expected.
$result contains only the object of resulting rows. To access the data, you need to fetch the row from result.
With the mysqli library:
With the mysql library using array: