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

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.

Related

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)

PHP custom function return value from mysql database

i have looked at the other results for what i'm trying to do, none of them do what i need them to. What i am trying to do is something like this:
myfunction(){
require('./connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='$user'"); //user is defined outside the function but it works in my login function which i use the same way.
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = row['value'];
mysql_close();
return $value;
} else {
$errmsg = "connection failed.";
$value = 0;
return $value;
}
}
In my php file i would do something like this at the top.
$value = myfunction();
This does not work.
Ultimately what i'm trying to accomplish is getting a value from the database and output it from the function in another file.
(this is my first post on stackoverflow so if i need to change this feel free to tell me and i shall)
Your code has several syntax error. Check this, and read my comments:
function myfunction() {
//connect to database
require('./connect.php');
//user is defined outside the function but it works in my login function which i use the same way.
$query = mysql_query("SELECT * FROM users WHERE username='" . mysql_real_escape_string($user) . "'");
$numrows = mysql_num_rows($query);
if ($numrows == 1) {
$row = mysql_fetch_assoc($query);
return $row['value']; //Missing $ sign
//No need to create $value if you just return with that.
//mysql_close();
//return $value;
} else {
//Where do you use this errmsg????
$errmsg = "connection failed.";
return 0;
// These 2 lines are unnecessary.
//$value = 0;
//return $value;
}
} //Missing function close
In my example, I've just leave the mysql functions, but please do not use them, they are deprecated. Use mysqli or PDO instead. Also, avoid sql injections by escapeing your variables!
$row = mysql_fetch_assoc($query);
$value = row['value']; // <-------- you forgot the $
and most probably, the correct way to extract the result is,
$row[0]['value'];
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
i'm thinking you forgot a dot here.
require('./connect.php');
And a bit of function improvement
myfunction(){
require_once('../connect.php'); //connect to database
$query = mysql_query("SELECT * FROM users WHERE username='".$user."'"); //user is defined outside the function but it works in my login function which i use the
$numrows = mysql_num_rows($query);
if($numrows == 1){
$row = mysql_fetch_assoc($query);
$value = $row['value'];
mysql_close();
}
else{
$errmsg = "connection failed.";
$value = 0;
}
return $value;
}

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

Whats wrong with mysql_num_rows? It is Returning errors

I used this series and I'm up to this video and mysql_num_rows has been pissing me off ever since the start.
http://www.youtube.com/watch?v=HP75yyjHgTg
i have easily spent 5 hours simply trying to fix all these mysql_num_rows errors.
At the Moment I'm doing profile page and I'm getting an error.
The Error is:
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /home/ztechrel/public_html/TESTING/blarg/REMAKE/profile.php on line 8 (line one is the mysql_num_rows part)
The Code in profile.php is:
<?php include("inc/incfiles/header.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysql_real_escape_string($_GET['u']);
if(ctype_alnum($username)) //check user exists
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1)
{
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
?>
is there a way i can fix this?
Or does anyone know another way i can write this?
I wouldn't be surprised he uses mysql_num_rows again, is there something i can use instead which is easy to implement?
If you need any other info just ask.
use this for checking error in your query
$username = mysql_real_escape_string($_GET['u']);
if(ctype_alnum($username)) {
//check user exists
$check = mysql_query("SELECT username,first_name FROM users
WHERE username='$username'") or die(mysql_error());
if(mysql_num_rows($check)===1){
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
Make sure you are capture errors from PHP.
It might be the previous statement mysql_query is not executed and hence result is not set.
Try with below if mysql_query is executing properly or note
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'") or die(mysql_error()."<br>".$sql);
This means your query returns nothing. Put echo for your query and display it in browser. Then copy the query and run it in phpmyadmin or mysql query browser or some other mysql editor. Try to find whether $username has correct value or any field name is wrong in the query.
Make sure variable $username is not empty., ctype_alnum is returning false. So $query is empty.
<?php include("inc/incfiles/header.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysql_real_escape_string($_GET['u']);
if ($username != "" && if(ctype_alnum($username))) {
$check = mysql_query("SELECT username,first_name FROM users WHERE username='$username'");
if(mysql_num_rows($check)===1)
{
$get = mysql_fetch_assoc($check);
$username = $get['username'];
$firstname = $get['first_name'];
}
else
{
echo "<h2>User Does Not Exist</h2>";
exit();
}
}
}
?>

Header redirects not working as expected

I have the following function which retrives the currently logged in users' username and finds out their access level from the database (either 'requested','user', or 'admin')
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if(isset($_SESSION['username']))
{
if($access == 'user')
{
return 1; // Returns 1 if access level is user
}
elseif($access == 'admin')
{
return 2; // Returns 2 if access level is admin
}
elseif($access == 'requested')
{
return 3; // Returns 3 if access level is requested
}
}
}
When I am checking whether the user is an admin using the follow code, this works correctly.
/* Redirects user if access level does not equal admin */
$result = fetchAccess();
if($result != 2)
{
header("location:index.php");
}
However when I check to see whether the access is 'requested' - this following is NOT working correctly.
<?php
/* Redirects user if access level does is 'requested' */
$result = fetchAccess();
if($result == 3)
{
header("location:redirect.php");
}
?>
Does anyone know why this is?
You can do this:
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
global $access
$access = $row['access'];
}
then:
global $access
if($access != admin){
header("location:redirect.php");
}
Have you verified that $result actually equal to 3? it may very well be that in the first instance $result == "" which is != 2 so it is not working at all. Try debugging it by including a header like:
<?php
$result = fetchAccess();
header("X-my-result: [$result]");
if ( $result == 3 ) {
header("Location: redirect.php");
}
?>
and see what you get back for value of $result in the headers.
do an echo statement to see what is return in the $result variable. btw, i'm not sure if your logic in your first redirect statement is to encompass both 'user' and 'requested', but those users will be redirected to index.php

Categories