Reputation: 188
I've got an Android project that uses a MySQL database for user registration and login. The registration portion works as expected. The login portion does not. Here's the thing, they both use the same EXACT query to check if an email address already exists. The registration checks to make sure that a user isn't already using that email address before storing the user. The login uses the same query to pull a hash of the encrypted password + salt to compare to the hash of the POSTED password hash. When the login portion makes the query, it returns at least one row, but it appears that all the values are null. Here's the code for where the query is:
// Check if user already exists.
$sql = sprintf("SELECT * FROM users WHERE email = '%s'", mysql_real_escape_string($email));
$result = mysql_query($sql) or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// User exists.
$stored_salt = $result["salt"];
$stored_password = $result["encrypted_password"];
$hash = crypt($password_hash, '$2a$10$'.$stored_salt);
// Check for password equality.
if ($stored_password == $hash) {
// User authentication details are correct.
$response["success"] = 1;
$response["uid"] = $result["unique_id"];
$response["user"]["name"] = $result["name"];
$response["user"]["email"] = $result["email"];
$response["user"]["created_at"] = $result["created_at"];
$response["user"]["updated_at"] = $result["updated_at"];
echo json_encode($response);
} else {
// User authentication failed.
// echo JSON with error = 1.
$response["error"] = 2;
$response["error_msg"] = "Incorrect password!";
echo json_encode($response);
}
} else {
// User does not exist.
$response["error"] = 1;
$response["error_msg"] = "Email address not found.";
}
The JSON object that is returned says "Incorrect password!", so I had it include the password that was being checked against in the JSON object, and that password is null. My assumption is that the query is not returning a result, but it passes the no_of_rows > 0 test, so it's returning something. So I included other parts of the result in the returned JSON object, and they're null as well. I also checked the query through phpmyadmin on my site (it's hosted on 1and1), and the query works there. Anyone have any insights? I'm new to both PHP and MySQL so I'm learning as I go here, but I've kind of hit a wall.
Upvotes: 0
Views: 1076
Reputation: 14243
You need to call mysql_fetch_assoc
or mysql_fetch_row
to get the actual row from the rowset back.
$sql = sprintf("SELECT * FROM users WHERE email = '%s'", mysql_real_escape_string($email));
$result = mysql_query($sql) or die(mysql_error());
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
// User exists.
$row = mysql_fetch_assoc($result);
$salt = $row['salt'];
Upvotes: 2