get ID for a specific user in mysql database in PHP - 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.

Related

Session value are not set in PHP

index.php
<?php
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select * from admin where email = '$email' and password = '$password'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from admin where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['admin_id'] = $rows['id'];
}
header ("Location: dashboard.php");
}
else
{
echo "<p id='red'>Wrong email or password.</p>";
}
}
}
?>
dashboard.php
<?php
session_start();
include('../config.php');
$admin_id = $_SESSION['admin_id'];
echo $admin_id;
?>
In this code I have create login form and initialize id into session variable when I echo $_SESSION['admin_id'] in index.php it return value but when I want to set $_SESSION['admin_id'] in dashboard.php but its not working or showing no value. How can I fix this issue ?Please help me.
Thank You
Add session_start(); to the top of index.php (inside the php tags of course)
session_start();
Is the session_start() already initialized in the index.php file? You should check that first. It's recommended that you place this in top of all files or a single included file in your script.
session_start();
Test if this fixes your problem.
Before set or get session in php you should always start session at the top of the page like below
session_start();
So in your code try to to start session in index.php
Add session_start() in index.php
<?php
session_start();
if(isset($_POST['submit']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "select * from admin where email = '$email' and password = '$password'";
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($result)
{
if ($num_rows > 0)
{
$sqls = "select * from admin where email = '$email' and password = '$password'";
$results = mysqli_query($con,$sqls);
while ($rows = mysqli_fetch_assoc($results))
{
$_SESSION['admin_id'] = $rows['id'];
}
header ("Location: dashboard.php");
}
else
{
echo "<p id='red'>Wrong email or password.</p>";
}
}
}
?>

Session Variables are lost after redirecting using header()

I have got index.php file that takes username and password from users, then it redirects to process_login.php that compares these credentials with SQL database to authorize the users. Now if the user is authorized, I want to get all the data about this user and want to use in other PHP files. I am using sessions to do so, but somehow they are not working.
I know they are so many similar questions, but none of them worked.
Here is my process_login.php code
<?php
session_start();
require_once('connectdatabase.php');
if(isset($_POST) && !empty($_POST)) {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
echo $count = mysqli_num_rows($result);
if($count == 1) {
$row = mysqli_fetch_assoc($result);
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}
else {
header('Location: ../../src/index.php');
}
}
?>
Now I want those variables on welcome.php file.
And this is my welcome.php code
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
It's because you are using $fist_name rather than $first_name. And edit your echo part
<?php
session_start();
$fist_name = $_SESSION['first_name'];
echo "<script>console.log('$first_name');</script>";
?>
To
<?php
session_start();
$first_name = $_SESSION['first_name'];
echo $first_name;
?>
I wanted to comment but I can't so here is my suggestion for you.
When something like your issue happens to me I tend to echo the $_SESSION all of them to see if they're actually set or not.
Below is a small PHP script which does the same but I'm using PDO as the DB API.
if (isset($_REQUEST["pWord"])){
$inmPword = md5($_REQUEST["pWord"]);
$loginData = "SELECT * FROM userlogin WHERE pWord = :pWord";
$loginDataQuery = $dbConnect -> prepare($loginData);
$loginDataQuery -> bindParam(':pWord', $inmPword);
$loginDataQuery -> execute();
if ($row = $loginDataQuery -> fetch(PDO::FETCH_ASSOC)){
//Time to set the session
$_SESSION["uId"] = $row["uId"];
$_SESSION["uRole"] = $row["uRole"];
$_SESSION["fName"] = $row["fName"];
$_SESSION["lName"] = $row["lName"];
echo "3";
}else{
echo "4";
}
}
I think it's better not do the row count and echo it. Something like this might help.
$sql = "SELECT * FROM users WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = mysqli_query($connection, $sql);
if($row = mysqli_fetch_assoc($result)) {
$_SESSION['first_name'] = $row["FIRST_NAME"];
$_SESSION['last_name'] = $row["LAST_NAME"];
$_SESSION['email'] = $row["EMAIL"];
$_SESSION['username']=$username;
header('Location: ../../src/welcome.php');
exit();
}

PHP Displaying user info when logged in

Alright, I have tried and searched everywhere to fix this but no luck.
All I am trying to do is display a users username and email (Who are logged in) and then print their details to thier account page.
The problem is that all of the users in the database are being logged, I only want the users who is logged in to be displayed.
Db.php
<?php
$myConnection= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($myConnection, "register") or die ("no database");
>
Auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
?>
Login.php
<?php
require('db.php');
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($myConnection, $username);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $password);
//Checking is user existing in the database or not
$query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
$result = mysqli_query($myConnection, $query) or die(mysqli_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION['user_id'] = $row['user_id'];
header("Location: index.php"); // Redirect user to index.php
}else{
echo "<div class='form'><h3>Username/password is incorrect.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Register.php
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$username = stripslashes($username);
$username = mysqli_real_escape_string($myConnection, $username);
$email = stripslashes($email);
$email = mysqli_real_escape_string($myConnection, $email);
$password = stripslashes($password);
$password = mysqli_real_escape_string($myConnection, $password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date) VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysqli_query($myConnection, $query);
if($result){
echo "<div class='form'><h3>You are registered successfully.</h3><br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
Account.php //Where I want user data to be displayed on page
<?php
// SQL query
$strSQL = "SELECT * FROM users";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>
$strSQL = "SELECT * FROM users";
Why that query? if you say you wanted to display only the info about users logged in, you are getting all users without conditions
Do the query for the user who is logged in at the moment, something like
$strSQL = "SELECT * FROM users WHERE username = '".$_SESSION['username']."'";
or somethinbg like this
<?php
session_start(); //Add this
//Also you have to add your connection file before your query
require('db.php');
// SQL query
$strSQL = "SELECT username, email FROM users WHERE user_id = '".$_SESSION['user_id']."'";
// Execute the query (the recordset $rs contains the result)
$rs = mysqli_query($myConnection, $strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysqli_fetch_array
while($row = mysqli_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['username'] . "<br />";
echo $row['email'] . "<br />";
}
// Close the database connection
mysqli_close($myConnection);
?>
I think it should have to work, tell me if it worked for you

Save $_SESSION on JQUERY $.POST

I have an HTML page in which I use Jquery .post() to post the forms into one big php file. I thought that this way I'll be able to save the username in a $_SESSION.
I have a login form that stores the username into a session, but then, when I try to display the php file (using .load()) in a different html page (linked to by the login one) I have no session variable set.
When I did a little debugging I found out the session is lost only if it's created in the if(isset($_POST['username'})) part of the page.
<?php
session_start();
include_once("connect.php");
$username = $_SESSION['username'];
//check if username is in session
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
?>
<div id="part_login">
<?php
//if not, check login
if(isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = md5($_POST['password']);
$result = mysqli_query($conn, "SELECT * FROM users WHERE username='$username' AND password='$password' AND active='1' LIMIT 1") or die(mysqli_error($conn));
$count = mysqli_num_rows($result);
if ($count == 1){
$_SESSION['username'] = $username;
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
echo "<script>$(document).ready(function(){location.replace('index.html#home')});</script>";
}else{
echo "<div class='ui-btn'>Invalid Login Credentials</div>";
}
}
}
if (isset($_SESSION['username'])){
$username = $_SESSION['username'];
$result = mysqli_query($conn, " SELECT * FROM `users` WHERE username = '$username'");
while($row = mysqli_fetch_array($result)) {
$oldlogin = $row['lastlogin'];
}
$query = mysqli_query($conn, "UPDATE `users` SET lastlogin=now() WHERE username='$username' LIMIT 1");
}else{
}
?>
</div>
<div id="part_user">
<?
echo $username . " " . $oldlogin;
?>
</div>

Retrieve data from database using session variable

<?php
{
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
echo $email;
$query = "SELECT uid FROM master WHERE emailid = '$email' ";
$result = mysql_query($query);
$row=mysql_fetch_array($result);
while($row)
{
$uid=$row[1];
echo $uid;
}
}
whats wrong in this code.it is giving the email but not able to retrieve uid using session variable email.
please help
while($row) {
$uid = $row[1];
echo $uid;
}
should be
while($row) {
$uid=$row['uid'];
echo $uid;
}
Try if this code works for you
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
//echo $email;
$query = "SELECT uid FROM master WHERE emailid = '$email' ";
$result = mysql_query($query);
while($row=mysql_fetch_array($result)){
$uid=$row['uid'];
echo $uid;
}
I don't know why you have { at beginning of your code, you should delete that. And second thing, delete echo $email; and you should have working code
try $uid=$row[0] instead of $uid=$row[1];
Because $row is an array.Array always starts its counter form 0.
here you have defined $uid=$row[1] which means it will display the result from second row of the result set..But there is no second row there is only one row which is "uid" so try $uid=$row[0] instead of $uid=$row[1];
try this:
<?php
session_start();
include "dbconnect.php";
$email = $_SESSION['email'];
$query = "SELECT uid FROM master WHERE emailid = '".$email."'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0)
{
$row = mysql_fetch_array($result);
$uid = $row["uid"];
echo $uid;
}
else
{
echo "No record found";
}
?>

Categories