Changing database field when user logs into account - php

I'm trying to update a database table to change a field when a user logs in. When the user inputs his/her correct information, a query runs to change the field from 0 to 1. However, this does not happen. I'm assuming that my query statement is wrong. Can anyone explain to me what I did wrong with the statement and what I should do to fix it?
<?php
session_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$user_name = "{$row['user_name']}";
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
$logged_in = "{$row['logged_in']}";
if(($user_id == $p_num) && ($pwd == $password)){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
$_SESSION["logged in"] = $logged_in;
mysqli_query($connect, "UPDATE '{$user_table}' SET logged_in = 1 WHERE user_id = '{$p_num}'");
header("Location: ../pages/instructor.php");
}
else{
header("Refresh: 1; URL=../index.php");
}
}
}
?>

I actually figured this out myself. I was simply checking for the wrong values in the sql statement.

Related

how to add user role in php

I tried to redirect my users and admin to some certain pages but my php code is redirecting both the admin and users to the same page
if (isset($_POST['Login'])) {
$username = $_POST['username'];
$password = $_POST['surname'];
$password_hash = md5($password);
$role;
if (!empty($username) && (!empty($password)))
{
$query = "SELECT 'id' FROM users WHERE 'staffno' = '$username' AND 'password'='$password_hash'";
$run = mysqli_query($conn, $query);
if ($run) {
$sql = "SELECT users.role FROM users";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_array( $result);
//$_SESSION['admin'] = $user['admin'];
$_SESSION['role'] = "admin";
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
header("location: Upload.php");
}else{
header("location: Home.php");
}
}
Try
if($run){
$_SESSION['role'] = $user['role'];
If($user['role'] == 'admin'){ //admin page}else{//the other page}
}
Also try limiting your result on your first query by adding
LIMIT 0, 1
Your code is now even short
Try to use this:
$_SESSION['role'] = $user['database-role-column-name'];
I'm assuming, you are session started at the top. Since, you have hardcoded $_SESSION['role'] variable
$_SESSION['role'] = "admin";
And, this always be true
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
You need to use instead
$_SESSION['role'] = $user['role'];
You need to stored dynamic user role in the session
$_SESSION['role'] = "admin";
change to
$_SESSION['role'] = $user['Your_User_Role_coulmn_name'];
This script $user = mysqli_fetch_array( $result); will return all information about selected user, so if you are storing user role in the same table then you can store the user role value in the session. In this way your if statement will be functional as per requirement.
Also for using session you need add session_start() before using $_SESSION.
Please check the example
session_start();
if (isset($_POST['Login'])) {
$username = $_POST['username'];
$password = $_POST['surname'];
$password_hash = md5($password);
$role;
if (!empty($username) && (!empty($password)))
{
$query = "SELECT `id` FROM users WHERE `staffno` = '$username' AND `password`='$password_hash'";
$run = mysqli_query($conn, $query);
if ($run) {
$sql = "SELECT users.role FROM users";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_array( $result);
$_SESSION['role'] = "admin"; // this approach will be always same
$_SESSION['role'] = $user['Your_User_Role_coulmn_name']; // you need to store dynamic user role into the session
if((isset($_SESSION['role']) && $_SESSION['role'] == "admin")){
header("location: Upload.php");
}else{
header("location: Home.php");
}
}
}
}
Can you start by changing $password = $_POST['surname']; to $password = $_POST['password']; and see if it solve your issue.

PHP get data from another page

I have a log in page.First, when the user enters the correct username and password he will move to managing page. But, I want to fetch his database information for another page. I mean I detect the username and password, then get other rows from that.
I know which I can use sessions, but session gives me one value and this is want I do not need.
<?php
if(isset($_POST['username'])){
if(isset($_POST['password'])){
$user_id = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM `users`");
while($row = mysql_fetch_array($result)){
$db_id = $row[0];
$db_user_id = $row["user_id"];
$db_user_pass = $row["user_pass"];
$db_user_type = $row["user_type"];
$db_user_name = $row["user_name"];
if($db_user_id == $user_id && $db_user_pass == $password && $db_user_type == "manager"){
header("Location: manager.php");
$_SESSION['currentmanager'] = $user_id;
}elseif($db_user_id == $user_id && $db_user_pass == $password && $db_user_type == "user"){
$_SESSION['currentuser'] = $user_id;
header("Location: users.php");
}elseif($db_user_id == $user_id && $db_user_pass == $password && $db_user_type == "teacher"){
$_SESSION['currentteacher'] = $user_id;
header("Location: teachers.php");
}
}
}
}
?>
$_SESSION['some_array'] = array(1,3,4);
as #u_mulder said.
Thanks.

executing queries using php

I'm the following query to verify the login information posted by the form. But whenever I run the query i get internal server error. I'm not sure what i'm doing wrong.
<?php
if(isset($_POST["userName"]) && isset($_POST["password"])){
$userName = $_POST["userName"];
$password = $_POST["password"];
include "http://evocature.com/scripts/db_connect.php";
$results = mysql_query("SELECT id
FROM admins
WHERE userName = '$userName'
AND password ='$password' LIMIT 1");
$existCount = mysql_num_rows($results);
if($existCount == 1){
while($row = mysql_fetch_array($results)){
$id = $row["id"];
}
$_SESSION["id"] = $id;
$_SESSION["manager"] = $manager;
$_SESSION["password"] = $password;
header("Location: http://www.evocature.com/admin/index.php");
exit();
}
else{
echo 'Invalid Information';
exit();
}
}
I belive you cant include http pages . Well not in this method .

Login suddenly stopped working

I'm working on my school project and I need a simple login functionality. It was working 20 minutes ago but then I perhaps made some mistake. It doesn't show any error message. The database seems to be alright.
'jmeno' = name, 'heslo' = password
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
$result = mysqli_query($mysqli, $sqllogin);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
I think you mixed post values. Try :
$username = $_POST['jmeno'];
$password = $_POST['heslo'];
I suggest debugging as follows:
<?php $mysqli = new mysqli("localhost","admin","admin","uzivatele");
if(isset( $_POST['heslo']) && isset($_POST['jmeno'])){
$username = $_POST['heslo'];
$password = $_POST['jmeno'];
/* defends SQL injection */
// $username = stripslashes($username);
//$password = stripslashes($password);
//$password = mysqli_real_escape_string($mysqli, ($_POST['heslo']));
//$username = mysqli_real_escape_string($mysqli, $_POST['jmeno']);
$sqllogin = "SELECT * FROM prihlaseni WHERE jmeno = '".$username."' AND heslo = '".$password."' LIMIT 1";
echo $sqllogin; //check the sql query string
$result = mysqli_query($mysqli, $sqllogin);
print_r($result);
if (!$result) {
die(mysqli_error($mysqli));
}
$count = mysqli_num_rows($result);
if ($count == 1) {
session_start();
$_SESSION['loggedin'] = true;
header('Location: home.php');
}else {
echo "<script language='javascript'>alert('Wrong password!');</script>";
}
}
?>
If sql string seems correct try querying the database directly and check output.
Probably there its not getting the $_POST vars, and not returning a valid $result.
Also I suggest you to not handle and save passwords like that but using hash functions like md5(string).

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories