check the log in if user or admin with php [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to check if the one who logged in is user or admin, I created a column in my DB named 'pin' and put the value whether 0 or 1.
if the pin in 0 so the logged in is an admin and user otherwise.
here is my code but it didn't work with me, please help, I'm totally beginner
$query = mysql_query("SELECT ID, password FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$query2 = mysql_query("SELECT pin FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$row2 = mysql_fetch_assoc($query2);
$check = $row2['pin'];
$rows = mysql_num_rows($query);
if ($rows == 1 && $check == 1) {
$_SESSION['login_user']=$ID; // Initializing Session
header("location: homeFM.php"); // Redirecting To Other Page
}
else if($rows == 1 && $check == 0) {
$_SESSION['login_user']=$ID; // Initializing Session
header("location: homeA.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}

Ok, so i rewrote what you have to try and make sense of it for you, with comments.
$query = mysql_query("SELECT ID, password, pin FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$row = mysql_fetch_assoc($query);
if(false != $row){ // user info exists/correct
$_SESSION['login_user'] = $row['ID'];
if('1' == $row['pin']) { //not admin
header("location: homeFM.php"); // Redirecting To Other Page
die;
} else { //admin
header("location: homeA.php"); // Redirecting To Other Page
die;
}
} else { //login doesn't exist
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
And that should work for you, hopefully the comments explain it. If it doesn't work, let me know, but it should according to the info you provided.
That being said....
I hope that your passwords are hashed, the input is sanitized, and that you look in to using PDO or MySQLi classes instead of the old deprecated mysql_ functions.
As a side note session_start(); is needed to start a session, not just assigning a variable within the super-global.

Error: There is 1 more closing curly braces '}' found
I'm guessing it is the last curly brace that needs removing
$query = mysql_query("SELECT ID, password FROM facultymember WHERE password='".$password."' AND ID=".$ID, $connection);
$query2 = mysql_query("SELECT pin FROM facultymember WHERE password='".$password."' AND ID=".$ID, $connection);
Your querys had weird concatenation

Related

Multi-user login trouble, also looking for good content on this topic

so i'm having trouble and i really have no idea why i'm having this issue because all looks well. But basically i'm trying create multiple user levels for a web page i'm making. For some reason only the regular user role is working at the moment. Basically I want admins to be led to a different user interface. If anyone knows any good content on how to make certain pages only available when a session is started that would be very helpful because that would be my next step after I solve this, also how to create a difference in regular user sessions and admin sessions if that makes sence... But back to my real problem, please tell me why admins arent being led to my admin.php page.. I'm posting the code below.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user = $_POST ['user'];
$pass = $_POST ['pass'];
$reg = '0';
$admin = '1';
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
//this query is for admin users **dont forget to change active to 1 within
db
$qa = "select * from users where username ='$user' and active = '0' and admin = '$admin'";
//this query is for regular users
$q = "select * from users where username ='$user' and active = '0' and admin
= '$reg'";
//these will run the querys above (a = admin)
$resulta = mysqli_query($conn, $qa);
$result = mysqli_query($conn, $q);
//will count rows and verify admin users
$numa = mysqli_num_rows($resulta);
$rowa = mysqli_fetch_array($resulta, MYSQLI_ASSOC);
//will count rows and verify regular users
$num = mysqli_num_rows($result);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($pass,$row['password']))
{
if ($num == 1) {
$_SESSION['username'] = $user;
header('location:index.php');
}
else if (password_verify($pass,$rowa['password']))
{
if ($numa == 1) {
$_SESSION['username'] = $user;
header('location:admin.php');
}
}
}
echo mysqli_error($conn);
?>
your code seems a little confusing to me, so I've sampled it down, instead of running two different queries, why not just one.
Look at this code below, this will help you transfer to admin page when admin logs in, and redirects you to regular page in case of all others.
All I am doing is checking the row value, instead of checking the count again.
<?php
session_start();
include 'db.php';
mysqli_select_db($conn, 'users');
$user=mysqli_real_escape_string($conn,$_POST['username']);
$pass=mysqli_real_escape_string($conn,$_POST['password']);
$hashedpassword = password_hash ($pass, PASSWORD_DEFAULT);
$sql="select * from users where username ='$user' and active = '0'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result, MYSQLI_ASSOC);
if(password_verify($mypassword, $row["pass"])) {
$_SESSION['username']=$user;
if($row["admin"] == "1")
header("location: admin.php");
else if($row["admin"]=="0")
header("location: index.php");
}
else
echo mysqli_error($conn);
?>

Only admin enters a page [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is my signin.php file
and I want to make a page which only admin (mousoufi) can enter.
I made a new page where I want to post only admin things can see. Else I wanted to echo to other users that they dont have permission here.
I just make a session on top of my admin page?
Any ideas?
<?php
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=new mysqli("localhost","root","","3333");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT username FROM `3333` WHERE password='$pass' AND username='$user'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
}
}
else {
echo "Wrong Password Try Again"; }
// Set session variables
$_SESSION["username"] = "$user";
$_SESSION["password"] = "$pass";
print_r($_SESSION);
if ("$user"=="mousoufi" AND "$pass"=="1234"){
echo "HELLO Mousoufi ";
}
$con->close();
?>
If you want to use sessions you need to start them on every single page that you need them on, and that is done with this:
session_start();
Put that at the top of your php script.
You'll need a way to distinguish admins (if you're going to have more than one?), but since your question only states one, this should work for you:
<?php
// start session
session_start();
// check if username is admin
if($_SESSION['username'] !== 'mousoufi'){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
Notes
You should have more readable table names. 3333 isn't really the best, especially when you call the table the same thing...
You should at least sanitize your user input variables - mysqli_real_escape_string() at very least. It'd be best if you go with PDO or MySQLi Prepared Statements.
Your script is wrong, badly wrong. If your user didn't log in correctly, don't set the session.
if (mysqli_num_rows($result) < 0) {
die("Wrong Password Try Again";);
} else {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
$_SESSION['username'] = $row["username"];
// and so on...
}
}
This is what your block should look like.

MYSQLI_NUM_ROWS doesn't return anything [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a table called "users" with 1 row.
I have been trying to get the number of rows that exist when the username and password have been entered. This wasn't returning anything, so I have created this code in the most simple form, but still it is not returning anything.
If I run the query on phpmyadmin, it returns the row.
Why could this not be working?
include("../includes/db.php");
$result = $link->query("SELECT * FROM users");
die(mysqli_num_rows($result));
The connection to the database is fine, all the other code works fine on my CMS.
edit:
This is my now working code:
include("../includes/db.php");
if(!isset($_SESSION['loggedin'])){
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = md5($_POST['password']);
$sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
$result = $link->query($sql);
if (!$result->num_rows == 1) {
echo "<p>Invalid username/password combination</p>";
LoginForm();
} else {
echo "<p>Logged in successfully</p>";
$_SESSION['loggedin'] = 1;
}
}else{
LoginForm();
}
}
include("../includes/db.php");
$result = $link->query("SELECT * FROM users");
echo $result->num_rows;
My bad for the previous answer. It's been a while since I've used PHP

Writing an 'if' statement in order to login users using php/ mysql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I’m wondering how you write if statements using mysql/php.
I’ve got an employee table with all their details, ‘username’ and ‘password’ then a column called ‘admin’ with a 0 or 1 as well. The user can login using the "username" and "password" form boxes. How do I write it so that it checks if the username/password exists then checks if admin = 0 and directs them to header location employee.php else if admin=1 then directs them to header location admin.php?
Any help would be greatly appreciated.
edit: This is the code I've got so far...
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
setcookie('username',$myusername,time() + (86400 * 7)); // 86400 = 1 day
if ('admin' == '0'){
header("location:employee.php");
}
else {
header("location:admin.php");
else {
header("location:fail.php");
}
}
?>
try this php code
$username = mysql_real_escape_string(stripslashes($_REQUEST['username'])); // received from post/get
$password = mysql_real_escape_string(stripslashes($_REQUEST['password'])); // received from post/get
$res = mysql_query("SELECT * FROM `employee` WHERE username='$username' AND password='$password' LIMIT 1") or die(mysql_error());
if($row = mysql_fetch_assoc($res))
{
if($row['admin']==1)
{
header("location:admin.php");
exit;
}
else
{
header("location:employee.php");
exit;
}
}
else
{
// invalid username or password
// code here to handle
}
You Can try using a select box of value ADMIN and USER . You can validate the select box in the if statement
if(select=="admin")
{
verify with DB \\admin
Redirect
}
else
{
verify with DB \\ end user
redirect
}
Hope it helps !!
You posted every step. Just code it now.
Make a new mysqli connection.
$mysqli = new mysqli("host", "user", "password", "database");
Define your query:
$query = "SELECT * FROM yourtablename WHERE username=? AND password=?";
Create a prepared statement:
$stmt = mysqli->prepare($query);
Bind the values:
$stmt->bind_param('ss', $submitted_username, $submitted_password);
Execute the statement:
$stmt->execute();
Check if there is a result or not.
If there is a result, check if admin is 0 or 1 and redirect (in case of 1) to admin php with header():
header('Location: admin.php');
You can get your selected data for example with fetch().
Just study the examples from php.net for more information how to get data with mysqli.

Unable to check for password and username at login

I have tried to create a PHP log in form. My code is as follows. The if-else statement is not functioning well. Please solve this.
$connect = mysql_connect("localhost", "root", ""); //connect
mysql_select_db("elective_mgmt", $connect);
$username = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * from verify_student where
username='$username' && password='$password'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if (name == $username && password == $password)
echo "you are logged in";
else
echo "please recheck your password and username";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0 ){
echo "you are logged in";
}
else
echo "please recheck your password and username";
You can also do this by counting the number of rows. In your code $row is an array so whenver you need to acces the array elements do this $row['name']
You have a problem here.
if(name==$username && password==$password)
It should be
if($row['name']==$username && $row['password']==$password)
OR
if(mysql_num_rows($result) == 1)
You should look at - Why shouldn't I use mysql_* functions in PHP?
You could remove your if/else statement since you check the inputs already with your mysql query (name && password) and replace it with a mysql_num_rows == 1 (as the others have already mentioned before).
It seems that you are new to php and creating log in forms, so let me give you a good advice:
input values for a log in form shouldn't be passed via URL, use method post instead
never save passwords unencrypted (use sha512 since md5 is considered unsafe)
never use single information to store the log in status in the session

Categories