I have table of users called users and log table called ulog. Every time when user signs in, the page adds new record into log table.
To prevent errors, before sign-in, I’m checking if user already signed in or not (I know that it’s not so important, there are other methods for this purpose: for ex, I can prevent it by checking for cookies or session too, but it’s interesting to me how can I do it with my idea).
The problem is code works perfectly if there is at least 1 row in ulog table about the user who currently trying to sign-in. If user wants to sign-in for the first time, the problem occurs: The code “flies over” the if ($stmt->num_rows > 0) { statements and selects else. (because num_rows returns 0)
How can I modify my query to handle in both situations: when user logs in for the first time, and for the second, third… time?
My php side sign-in code looks like that.
$stmt = $db->prepare("SELECT u.id, u.fname, u.lname, u.mname, u.level, u.pass, u.salt, u.approved, u.ban, u2.logged_in FROM `users` AS u, `ulog` AS u2 WHERE u.email=? AND u2.user_id=u.id") or die($db->error);
$stmt->bind_param("s", $email) or die($stmt->error);
$stmt->execute() or die($stmt->error);
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $fname, $lname, $mname, $level, $db_pass, $salt, $approved, $ban, $logged_in) or die($stmt->error);
$stmt->fetch() or die($stmt->error);
if ($logged_in == 0) {
}
else die("You're already logged in");
}
else die("There is no such email in db");
Trying doing a left outer join of the log table. This will return null for the first time they try and log in, because there is nothing in the log table for them. You will also need to do null checking on $logged_in, as this is a case. The easier thing to do would be to check for 1 in the $logged_in var to validate that they are logged in, as anything other than 1 would mean they were not logged in.
Here is your first line redone:
Try that out, see if it does what you need. Left outer joins basically state Show me AT LEAST everything that comes back in the FROM table(s). if there is anything in the LEFT OUTER JOIN table(s), tack that on too