Undefined variable error in my PHP script - php

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 .

Related

include user ID in session

Currently my php login form will only carry acrocss the username on the session, I want this to carry across the user id (automatically created when the user registers).
As shown below I have included the user_id but it is not displaying on my webpage, the username is however.
Just wondering if anyone can help me with this? (I'm new to PHP)
Login process:
require_once('connection.php');
session_start();
if(isset($_POST['login']))
{
if(empty($_POST['username']) || empty($_POST['PWORD']))
{
header("location:login.php?Empty= Please Fill in the Blanks");
}
else
{
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if(mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];
header("location:../manage_event.php");
}
else
{
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
}
else
{
echo 'Not Working Now Guys';
}
Session on next page:
session_start();
if(isset($_SESSION['User']) || isset($_SESSION['user_id']))
{
echo ' Welcome ' . $_SESSION['User'].'<br/>';
echo ' User ID ' . $_SESSION['user_id'].'<br/>';
}
else
{
header("location:login/login.php");
}
Though your security is questionable, i’ll answer your question anyway. As stated in another response you aren’t assigning your variables the right way. See an example here
The following code will fix your problems contrary to the other solution:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
if ($result = mysqli_query($con, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id']=$row['user_id'];
header("location:../manage_event.php");
}
}else {
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
Make sure to replace this code with your old fetching code block. Thus in the first ‘else’ clause.
How about assigning the fetched result to $row:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if( $row = mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];

Different Access levels for users by using PHP & MySQL

I am developing a website for testing with logging page with different access levels for users, the site is connected with MySQL db which have 3 columns
user | password | level(1/2)
code is filter out the particular entry from db but it didn't redirected to particular page. i tested with echo but at the $count it shows 0 . please help me to sort this out, I am going to use mysqli instead at the launching phase.
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('udb',$conn);
$sql = "SELECT * FROM logins WHERE user ='".$username."' AND password = '".$password."'";
$result = mysql_query($sql,$conn);
echo $result;
$count = mysql_num_rows($result);
if ($count==1) {
$_SESSION['login_user']=$username;
while ($row = mysql_fetch_array($result)){
if ($row['level'] == '2') {
header("home2.php");
} else {
header("home1.php");
}
}
}
Your echo $result; will prevent any further redirect down in the code. It is due to the fact that redirects are managed using headers... but since you output some data ... headers can not be managed.
no need to give connection variable in mysql_query() and in header function u forgot to pass location
$sql = "SELECT * FROM logins WHERE user ='".$username."' AND password = '".$password."'";
$result = mysql_query($sql);
//echo $result;
$count = mysql_num_rows($result);
if ($count==1) {
$_SESSION['login_user']=$username;
while ($row = mysql_fetch_array($result))
{
if ($row['level'] == '2')
{
header("location:home2.php");
} else {
header("location:home1.php");
}
}
}
You need to use location if you want your redirects to work.
if ($row['level'] == '2') {
header("location: home2.php");
} else {
header("location: home1.php");
}
Your script is at risk for SQL Injection.
If you can, you should stop using mysql_* functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's really not hard.
Finally, you should use the proper methods to hash passwords with PHP. The way that you're handling login is extremely insecure.
Place the user and password into back ticks (apostrophe marks on the left of key 1)

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."'";

creating two different sessions in PHP

I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.

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