If statement if no value returned - php

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.

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";
}

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).

$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

Related

Unique identifier link value receiving failure in PHP isset GET

I'm trying to verify registration via email with sending of unique identifier link to user.
I use it from remote server. Server, username, password, database values are correct, works fine with other .php-s, only difference verify.php has connection included, instead require 'connection.php';, but I'm not sure if connection produces following failure.
Sends:
$message = "<p>Hello, dear $user</p><a href='https://mypage.info/php/reg/verify.php?vkey=$vkey'>Confirm Account</a>";
and receives on email:
https://mypage.info/php/reg/verify.php?vkey=4bf65cf02210b304143589e6dc3714c0
link to verify.php, but php throws Something went wrong, or
if instead die I'll check echo 'VKey: '. $vkey; or echo $mysqli->error; shows nothing.
Seems like by some reason if (isset($_GET['vkey'])) does not receives vkey correctly. I'm not sure what I'm doing wrong here:
Alert! This example code shows insecure method since accepts SQL parameters directly from user input. Requires Prepared Statements and Bound Parameters, real_escape_string()
<?php
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
$mysqli = NEW MySQLi ('server','username','password','db');
$resultSet = $mysqli->query("SELECT verified, vkey FROM registration WHERE verified = 0 AND vkey = '$vkey' LIMIT 1");
if ($resultSet->num_rows == 1)
{
$update = $mysqli->query("UPDATE registration SET verified = 1 WHERE vkey = '$vkey' LIMIT 1");
if($update){
echo "Your account has been verified. You may now login.";
} else {
echo $mysqli->error;
}
}
else
{
echo "This account invalid or already verified";
}
} else {
die("Something went wrong");
}
?>
Your code looks in the $_POST array instead of $_GET
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
SUGGESTION: instrument everything possible, and post back what you find.
For example:
<?php
echo "vkey=" . $_GET['vkey'] . "...<br/>";
if (isset($_GET['vkey'])) {
$vkey = $_GET['vkey'];
echo "vkey=" . $vkey . "...<br/>";
$mysqli = NEW MySQLi ('server','username','password','db');
echo "mysqli: SUCCEEDED...<br/>";
$resultSet = $mysqli->query("SELECT verified, vkey FROM registration WHERE verified = 0 AND vkey = '$vkey' LIMIT 1");
echo "resultSet: SUCCEEDED...<br/>";
echo "resultSet->num_rows=" . $resultSet->num_rows . "...<br/>";
if ($resultSet->num_rows == 1)
{
$update = $mysqli->query("UPDATE registration SET verified = 1 WHERE vkey = '$vkey' LIMIT 1");
echo "update: SUCCEEDED...<br/>");
if($update){
echo "Your account has been verified. You may now login.";
} else {
echo $mysqli->error;
}
}
else
{
echo "This account invalid or already verified";
}
} else {
echo "ERROR STATE: " . $mysqli->error . "...<br/>";
die("Something went wrong");
}
?>
And no, I can't think of "... why md5 string" could be the culprit. But I think the above instrument (or similar) might help us determine EXACTLY where the problem is occurring ... and thus how to resolve it.
'Hope that helps...

How to debug PHP database code?

I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";

If statement ignoring elseif

I have this if statement. It is part of a php script that is run when a button is clicked to determine the page it is forwarded to.
I have a table that is updated when an admin changes the page and this all works fine.
For some reason however this is always forwarding to scriptone. Even though for instance scriptthree is definately selected.
Any suggestions please?
$sql = "SELECT scriptName FROM selectedscript WHERE scriptSelected = '1'";
if($sql = "ScriptOne") {
header('Location: scriptone.php');
}
elseif ($sql = "ScriptTwo") {
header('Location: scripttwo.php');
}
elseif ($sql = "ScriptThree") {
header('Location: scriptthree.php');
}
else {
echo "Error";
}
Thank you
I have tried double and triple equal signs however that leads to the Error message being displayed :(
= is assignment. == is equality. === is strict equality. You want one of the latter as the first typically results in a true value.
if ($sql == "ScriptOne") {
header('Location: scriptone.php');
}
You'll need to perform the sql query and fetch some values before using them in your if statements.
Something like this:
$sql = "SELECT scriptName FROM selectedscript WHERE scriptSelected = '1'";
$q=mysql_query($sql) or die(mysql_error());
$row=mysql_fetch_assoc($q);
switch ($row['scriptName']) {
case 'ScriptOne':
header('Location: scriptone.php');
break;
case 'ScriptTwo':
header('Location: scripttwo.php');
break;
case 'ScriptThree':
header('Location: scriptthree.php');
break;
default:
echo "Error";
}
Also, consider using PDO instead of mysql_* statements as they are depreciated.
if($sql == "ScriptOne") {
^
not
if($sql = "ScriptOne") {
= is assignment, == is comparison
You need to use double or triple equal signs
if($sql == "ScriptOne") {

Undefined variable error in my PHP script

What is the problem with following code? Please help me out.
I want to match admin-id and password from the database along with login-id and password of the normal users and further want to transfer the control to the respective forms.
When I run this code it gives following errors:
Notice: Undefined variable: userstatus in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 25
Notice: Undefined variable: usertype in C:\xampp\htdocs\xampp\Test\HRMS\extract.php on line 30
$query1="select user_type,user_staus from `user_info` where name='$username' and
password='$password'";
$fetched=mysql_query($query1);
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
if($userstatus==1) //if is logged in already
{
echo "Please login after some time";
exit();
}
if($usertype == 0) // if user is not an admin
{
$query1="select * from `user_info` where name='$username' and password='$password'";
$result = mysql_query($query1);
if(mysql_num_rows($result) == 1)
{
header("Location: user_form.php");
}
}
else if($usertype == 1) //if the user is a normal user
{
header("Location: admin_form.php");
}
else
{
echo "please register to login";
}
Can someone help me find the problem?
There are many problems with your code, main reason you receiving an error is because $usertype and $userstatus are not predefined and not validated.
But in my opinion it is not a main issue with your code.
There are few questions that I would like to ask you:
Why creating two loops if you need to fetch a single row?
Why querying database twice if you already know the answer?
Are you escaping $username and $password for bad characters using mysql_real_escape_string method?
here is an example how this code should look like:
$query1 = "SELECT user_type,user_staus FROM `user_info` WHERE name='{$username}' AND password='{$password}' LIMIT 1";
$fetched = mysql_query($query1);
//check if record exists otherwise you would receive another notice that can
//break redirect functionality
if (mysql_num_rows($fetched))
{
$record = mysql_fetch_assoc($fetched);
// make sure that value is integer
if ((int)$record["user_staus"])
{
exit("Please login after some time");
}
else
{
$url = (bool)$record["user_type"] ? 'admin_form.php' : 'user_form.php';
header("Location: {$url}");
exit(0);
}
}
else
{
echo "please register to login";
}
UPDATE
As suggested by nikc.org, removed 3rd level if nesting and replaced with ternary comparison
you have overlooked the scope rules ( since you have not shown full code)
while($record=mysql_fetch_assoc($fetched))
{
while(each($record))
{
$usertype=$record["user_type"];
$userstatus=$record["user_staus"];
}//closing of 1st while loop
}//closing of 2nd while loop
Here $usertype and $userstatus are declared inside inner while loops { } .
ie, their scope resorts to that { } . as soon as code comes out of it the $userstatus and $usertype dies and so further accessing is not possible .
you must declare there variables ut side in global area first .

This if statement isn't working - what am I doing wrong?

I'm trying to retrieve the access level (admin/member/guest) for the currently logged in user and depending on this, show them specific content on my page. I'm trying to test this with echos right now but still cannot get anything to print out. Could anyone give any advice?
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' ";
$result = mysql_query($q, $con);
if($result == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($result == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($result == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result is a mysql resource. you need
if(isset($_SESSION['username'])){
global $con;
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if($access == 'guest')
{
echo "You are a guest";// SHOW GUEST CONTENT
}
elseif($access == 'member')
{
echo "You are a member"; // SHOW OTHER CONTENT
}
elseif($access == 'admin')
{
echo "You are an admin";// SHOW ADMIN CONTENT
}
}
$result as returned by mysql_query is not a string that you can compare against; it is a resource. You need to fetch the row from $result:
$row = mysql_fetch_assoc($result)
$access = $row['access'];
if($access == 'guest') {
...
}
...
A few other issues:
You have a possible SQL-injection issue in your query. You should never directly insert the values of variables into your SQL queries without properly escaping them first. You might want to use mysql_real_escape_string.
The mysql is being deprecated. You should try to use mysqli (MySQL Improved) or PDO (PHP Data Objects).
I see two issues:
1. You need to use session_start(); at the beginning. otherwise your if statement will not be executed.
2. mysql_query($q, $con) does not return a string. it returns a record set. You need to use mysql_fetch_assoc($result); which return associative array.And from the array you retrieve your desired value by:
$assoc_arr = mysql_fetch_assoc($result);
$access = $assoc_arr['access'];
now you can compare $access.

Categories