Getting id from database and put it in session id - php

For my website I need to be able to get an ID from a database after someone logged in. I already figured out how to put the variables from the login page into a session but I cant figure out how to write a code that gets an ID from a database and turns it into a session variable.
session_start();
include( "connection.php" );
if(isset($_GET['action']) && ($_GET['action'] == "login")){
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$pass = mysqli_real_escape_string($conn, md5( $_POST['pass'] . "90qdjka*#"));
$QUERY = "SELECT * FROM users WHERE username = '$name' AND password = '$pass' AND enabled = 1";
$EXEC = mysqli_query($conn, $QUERY );
if(mysqli_num_rows($EXEC)==0){
die( 'Login niet geldig! Opnieuw inloggen' );
}else{
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
$QUERY = "UPDATE users SET lastlogin=NOW() WHERE username = '$name' AND password = '$pass'";
mysqli_query($conn, $QUERY);
}
}
?>

else{
if (mysqli_num_rows($EXEC) > 0) {
while($row = mysqli_fetch_assoc($EXEC)) {
$_SESSION['id'] = $row["id"];
}
}
$_SESSION['name'] = $name;
$_SESSION['pass'] = $pass;
if your query returns only one result then while loop will run only one time but if your query returns more than one record then the last record's id will be stored in your session variable
In $row["id"], id is the column name of the table, if you are selecting all columns from your table and if your users table has columns like name, username, password then you can access it using $row["name"], $row["username"], $row["password"]

Related

how can i call a function that return user array from their id from another file?

This functions is used to get id of the created user
$logged_in_user_id = mysqli_insert_id($db);
$_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
This is the function declared that return user array from their id:
function getUserById($id){
$query = "SELECT * FROM users WHERE id=" . $id;
$result = mysqli_query($db, $query);
$user = mysqli_fetch_assoc($result);
return $user;
}
//I'm trying to call it in this file:
//update.php
<?php
include('functions.php');
$id=$_GET['id'];
$id= getUserById($id);
$view = "SELECT * from users where id = '$id'";
$result = mysqli_query($db,$view);
$row = $result->fetch_assoc();
if (isset($_POST['update'])) {
$id= $_SESSION['id'];
$username= $_POST['username'];
$email= $_POST['email'];
$insert= "UPDATE users set username= '$username',
email = '$email' where id='$id'";
if ($db->query($insert) ==TRUE) {
echo "Sucessfully update data";
header('location:update.php');
}else{
echo "Ooppss cannot add data" . $db->error;
header('location:update.php');
}
$db->close();
}
?>
the first code is where you can see :This functions is used to get id of the created user
the second one is where you see the the function declared that return user array from their id
please can someone help me with this?

Create a current session variable not working

I have a table and it has more columns:
id | username | picture
Picture is varchar type and it keeps the path of user picture
username is varchar and is unique
<?php
session_start();
if (isset($_POST["logIn"])) {
$connection = new mysqli(...);
$email = $connection->real_escape_string($_POST["email"]);
$password = sha1($connection->real_escape_string($_POST["password"]));
$data = $connection->query("SELECT * FROM users WHERE email='$email' AND password='$password'");
if ($data->num_rows > 0) {
$_SESSION["email"] = $email;
$_SESSION["loggedIn"] = 1;
$picture = $connection->query("SELECT picture FROM users WHERE email='$email' AND password='$password'");
$_SESSION["picture"]=$picture;
header("Location:../index.php");
exit();
}
So what I want to do is, create a $_SESSION["picture"] variable which will keep the value of the username's picture , i mean the picture of the user that is trying to login now
You have to call a fetch function to get the data from the table.
$data = $connection->query("SELECT picture FROM users WHERE email='$email' AND password='$password'");
if ($data->num_rows > 0) {
$row = $data->fetch_assoc();
$_SESSION["email"] = $email;
$_SESSION["loggedIn"] = 1;
$_SESSION["picture"]=$row['picture'];
header("Location:../index.php");
exit();
}

How to store a return result from an SQL statement in a PHP session variable

I was here yesterday with the same issue, but I have changed the code slightly. I am trying to fetch the user id of a user as they log in and store it as a session variable. I don't know what I'm doing wrong though, as when I try pass this session variable into another SQL INSERT statement in a different php file, it does not work. If I pass a local variable to the INSERT statement it works and inserts all values into my database. When I try pass the session variable, it does not work.
This is my login file where I declare the session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn'])) {
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
$id_retrieve = mysqli_query("SELECT user_id FROM userdetails WHERE email='$email'");
$retrieved_id = mysqli_fetch_row($id_retrieve);
$password = md5($password);// Decrypt hash of password stored in database
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
if (mysqli_num_rows($resultOfQuery) == 1) {
$_SESSION['user_id'] = $retrieved_id[0];
header("location: User_Home_Page.html");
}else{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
}
}
?>
This is the file where I then try insert this session variable:
<?php
session_start();
$db =mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['upload_btn'])){
$user_id = $_SESSION[ 'user_id' ];
$taskTitle = mysql_real_escape_string($_POST['tasktitle']);
$taskDescription = mysql_real_escape_string($_POST['TaskDescription']);
$file = rand(1000,100000)."-".$_FILES['file_document']['name'];
$file_loc = $_FILES['file_document']['tmp_name'];
$file_size = $_FILES['file_document']['size'];
$file_type = $_FILES['file_document']['type'];
$folder="uploads/";
move_uploaded_file($file_loc,$folder.$file);
$numPages = mysql_real_escape_string($_POST['number_of_pages']);
$numWords = mysql_real_escape_string($_POST['number_of_words']);
$deadlineClaim = mysql_real_escape_string($_POST['deadline_claim']);
$deadlineComplete = mysql_real_escape_string($_POST['deadline_complete']);
$sql = "INSERT INTO task(user_id, title, description, file, file_type, file_size, pg_num, num_words, deadline_claim, deadline_completion) VALUES( '$user_id', '$taskTitle', '$taskDescription', '$file', '$file_type', '$file_size', '$numPages', '$numWords', '$deadlineClaim', '$deadlineComplete')";
mysqli_query($db, $sql);
header("location: User_Home_Page.html");
}
?>
If someone could provide a solution I would really appreciate it.
First you don't need 2 query because you need a query where you get user_id based on data where user must login.
So in this query first u check for email and password to match that user and if this match u will get more that 0 based on mysqli_num_rows.
When u check this and this works you use mysqli_fetch_array so you can use a data from it however you want.
You can remove error_reporting, ini_set, var_dump if its all ok, this is just for testing and to give you error if exists
Here is your code:
<?php
// turn on error reporting
error_reporting(1);
ini_set('error_reporting', E_ALL);
// start session
session_start();
// debug session
var_dump($_SESSION);
// database connection
$db = mysqli_connect("localhost", "root", "", "project_website1");
if(isset($_POST['Login_Btn']))
{
$email = mysql_real_escape_string($_POST['email']);
$password = mysql_real_escape_string($_POST['password']);
// Decrypt hash of password stored in database
$password = md5($password);
// get all data from userdetails table
$mySQLQuery = "SELECT * FROM userdetails WHERE email='$email' AND password='$password'";
$resultOfQuery = mysqli_query($db, $mySQLQuery);
// if query return more that 0 rows
if (mysqli_num_rows($resultOfQuery) > 0)
{
// fetch data
$uid = mysqli_fetch_array($resultOfQuery);
$_SESSION['user_id'] = $uid['user_id'];
header("location: User_Home_Page.html");
exit();
}
else
{
$_SESSION['message'] = "Login Fail";
header("location: User_Login.html");
exit();
}
}
?>
EDIT :
Don't use md5 its not secure use password_hash() and password_verify() to make yours password safe.

get ID for a specific user in mysql database in PHP

When a user signs in i want to echo back there ID (which is created because of the auto_increment in phpMyAdmin) from there account, here's my login.PHP:
<?php
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
echo "Welcome: Buyer";
}else{
$int = 1;
//echo "Buyer login failed...";
}
}else{
echo "Login failed...";
}
}
mysqli_stmt_close($statement);
mysqli_close($conn);
?>
Add the column name id in your sql query.let say your column name for id is ID
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
echo $user_id;
echo "Welcome: Buyer";
}
Since your making login in php its good choice to use $_SESSION.
All you need to do is add a session_start(); at the top of any php script where you need to use session.
<?php
session_start();
$conn = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$Email = $_POST["Email"];
$Password = $_POST["Password"];
$sql_query = "select ID,Buyer_Email from user_info where Buyer_Email like '$Email' and Buyer_Password like '$Password';";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0 ){
$row = mysqli_fetch_assoc($result);
$name = $row["Buyer_Email"];
$user_id = $row['ID'];
//using session
$_SESSION["user_id"] = $user_id;
echo $user_id;
echo "Welcome: Buyer";
}
Now you can access anywhere in your php script using the $_SESSION variable.
echo $_SESSION["user_id"] ;
Let's start from the beginning. You create a login form, you store sessions based on the values:
login.php
session_start();
$_SESSION["username"] = $username;
main.page
$username = $_SESSION["username"];
echo "Hi $username";
EDIT 2
Ok, so you want to check if username exists and then echo their ID. Regardless, almost all login systems have sessions.
After logging in, let's say you have a $_SESSION of id.
php
session_start();
$id = $_SESSION["id"];
$db = mysqli_connect("xxxxxx", "xxxxx", "xxxx", "BuyerAccounts");
$check = $db->query("SELECT * FROM users WHERE id='$id'");
$num_check = $check->num_rows;
$fetch_check = $check->fetch_object();
$id2 = $fetch_check->id;
if($num_check) {
// User Exists
echo $id2;
} else {
echo "You don't exist."
}
Please note, normally, I would just echo $id. However, the OP requested to echo the id from the db, so I echoed $id2.

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