Reputation: 85
So, I have this:
$user = $db->prepare("SELECT * FROM `users` WHERE LL_IP='" . $_SERVER['REMOTE_ADDR'] . "'");
$user->execute();
while($userDATA = $user->fetch(PDO::FETCH_ASSOC)) {
if( userDATA['LL_IP'] == $_SERVER['REMOTE_ADDR']) {
echo "Logged in";
}
else {
echo "Register / Login";
}
}
I'm trying to get it where if no $userDATA['LL_IP']
is found. Then it does the else
statement, but for some reason it's not working.
I've also tried:
elseif($userDATA['LL_IP'] == false) {
echo "Register / Login";
}
But that doesn't work either.
Upvotes: 0
Views: 49
Reputation: 71384
Your logic is faulty. You already query only for cases where LL_IP
equals $_SERVER['REMOTE_ADDR']
. Why would expect to EVER gat a result turned where your if conditional wouldn't match.
It seems to me that all you would need to do in this case is to check to see if the number of records returned in the result set is greater than 1.
By the way, you should at least escape $_SERVER['REMOTE_ADDR']
before using it in a query, or better yet, since you are already using a prepared statement, you could use a parametrized value.
Your logic should be something like this:
// specify maybe a primary key field in query. No need for SELECT *
$query = "SELECT COUNT(user_id) FROM `users` WHERE LL_IP = :ip_address LIMIT 1";
$user->prepare($query);
$user->bindParam(':ip_address', $_SERvER['REMOTE_ADDR'], PDO::PARAM_STR]);
$user->execute();
if('1' === $user->fetchColumn(0)) {
// logged in
} else {
// not logged in
}
I also agree with comment from @jeroen above that you really shouldn't rely on an IP address to determine any sort of login status. IP addresses can change unpredictably (particularly for mobile users).
Upvotes: 1
Reputation: 32532
$user = $db->prepare("SELECT * FROM `users` WHERE LL_IP='" . $_SERVER['REMOTE_ADDR'] . "'");
$user->execute();
if ($user->fetchColumn() > 0) {
// logged in
} else {
// not logged in
}
The manual (see example #2) says to use fetchColumn
Upvotes: 0
Reputation: 91734
If you just want to check if a row was found, you can replace the loop with an if
statement:
if($userDATA = $user->fetch(PDO::FETCH_ASSOC))
{
echo "Logged in";
}
else
{
echo "Register / Login";
}
Upvotes: 2