Getting user data from session - php

I made a login system and it works but I also have the user's session in the page after login.
How can I get user data from my database by referencing the user's session, and how can I update it when the user put what they going to change
<?php
session_start();
$query=mysql_query("SELECT username, email, password FROM user WHERE username = $_SESSION['username']");
while($row = mysql_fetch_array( $query )) {
echo .row['username'];
echo .row['email'];
echo .row ['password'];
?>

In new codes you should be using mysqli if your PHP version is high enough (if not... update...)
But here you go:
<?php
session_start();
$query = mysql_query("SELECT * FROM user WHERE username = {$_SESSION['username']}");
$row = mysql_fetch_assoc($query);
echo $row['username'];
echo $row['email'];
echo $row ['password'];
?>
Oh and the update:
<?php
$query = mysql_query("UPDATE user SET username={$_POST['username']}, email={$_POST['email']}, password={$_POST['password']} WHERE username={$_SESSION['username']}");
?>
And you should make a form for that..

The answer of Cris is almost perfect and well explained. But it is missing the quotes for the string in the statement.
As the col username will most likely be a varchar of any length.
$query = mysql_query("SELECT * FROM user WHERE username = '{$_SESSION['username']}'");

Related

display user profile from mysql database with php sessions [duplicate]

This question already has answers here:
How can I get an unknown username given an ID?
(2 answers)
Closed 1 year ago.
am new here, i have an issue with displaying logged in user profile, hoping you guys can help, here is my code :
<?php session_start(); include 'dpconfig.php'
<?php $run = mysqli_query($conn,"Select * from user Where id = $_SESSION['uid]");
$row = mysqli_fetch_array($run, MYSQLI_BOTH); { }
$showid = $row[0];
$showfirst = $row[1];
$showlast = $row[2];
$showuid = $row[3];
echo $showid; echo $showfirst; echo $showlast; echo $showuid;
Now basically this code gives me the details of the first id in my database even if i login different users, i need help selecting data from table name(user) to display logged in user profile, using sessions. Thanks
$run = mysqli_query($conn,"Select * from user where username='xxx' and pass='xx'");
it will return login user detail.
Try something like this, you need to remember to check that the array holds values as well, then you can respond to it...
$conn = dbconfig;
$id = $_SESSION['id'];
$sql = "SELECT * FROM user WHERE id='$id'";
$check = mysqli_query($conn, $sql) or die ("err $id " . mysqli_error ($conn));
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
while ($row = mysqli_fetch_assoc($check)) {
$userid = $row['id']; // repeat for all db columns you want
}
}
Sorry if there are any typos, done this on my phone quickly. If you need further help gimme a shout.
Updated the code to show more information with the error message, to help you get to the bottom of why it's not working for you.

I suspect a PHP-SQL error in the code below

This block of codes is supposed to retrieve data from my database using password already stored in the table. For some passwords, entered via a web form, it behaves properly. For others, it doesn't. I spent a good time trying to fix it, but could not.
<?php
include('connect.php');
$login = $_POST['login'];
$query = mysql_query("select * from secure_table where myPass = $login");
$row = mysql_fetch_array($query));
if( $_POST['login'] = $row['myPass'])
{
echo"<div align ='center'>";
echo "Your Details are:";
echo $row['surName'];
echo"<br/>";
echo $row['firstName'];
echo"<br/>";
echo $row['myDepartment'];
echo"</div>";
}
else{
echo "<div align = 'center'>;
<h2>Error in Password</h2>
</div>";
}
mysql_close($connection)
?>
and you need to change this line as well
if( $_POST['login'] = $row['myPass'])
To this
if( $_POST['login'] == $row['myPass'])
//use double equal for comparison. single equal is assignment operator.
$query = mysql_query("select * from secure_table where myPass = $login");
your query is wrong if $login is not and integer
change to this
$query = mysql_query("select * from secure_table where myPass = '$login'");
check this link
http://dev.mysql.com/doc/refman/5.0/en/identifier-qualifiers.html
you have extra ) remove this in this line
$row = mysql_fetch_array($query));
to this
$row = mysql_fetch_array($query);
as it written and The One and Only ChemistryBlob pointed it out remove the semicolumn ; in the
else statement from this line
echo"<div align = 'center'>;
one more think mysql_ function are depricited.
use mysqli_ Function or PDO
For mysqli_ function check this link http://php.net/manual/en/book.mysqli.php
FOR PDO check this link http://php.net/manual/en/book.pdo.php

Load data from multiple columns in Joomla

I've been stuck with this problem. I have a form where the user will enter his/her input. Based on that input, a query is done to the database that will return matching results.I
t's fairly simple but couldn't find a way to do it.
I manage to load the data using loadResult().
But now since I want to load from multiple columns, loadResult() is a no go.
<?php
$db = JFactory::getDbo();
$name = JRequest::getVar('name');
$query="SELECT username FROM jos_users WHERE name='$name'";
$db->setQuery($query);
echo $db->loadResult();
?>
That was my code when I was using loadResult(). No problem.
But now I want to load username and status from the query. How can I do that?
I tried putting in
<?php
$db = JFactory::getDbo();
$name = JRequest::getVar('name');
$query="SELECT username, status FROM jos_users WHERE name='$name'";
$db->setQuery($query);
$db->loadObject($name);
echo "Username : $name->username";
echo "Status : $name->status";
?>
But returns an error.
Try change:
$db->loadObject($name);
echo "Username : $name->username";
echo "Status : $name->status";
to:
$row = $db->loadRowList();
echo "Username : ".$row['username'];
echo "Status :".$row['status'];
Your code is supposed to be like this.
You have to store return value in a variable and then you can use it. But in your code you are trying to print value with the params send to loadObject method.
<?php
$db = JFactory::getDbo();
$name = JRequest::getVar('name');
$query="SELECT username, status FROM jos_users WHERE id='$name'";
$db->setQuery($query);
$row = $db->loadObject();
echo "Username : $row->username";
echo "Status : $row->status";
?>

Display users First and last name in plain text from the database or give an error

I have a html page that sends value pass to log.php :
<?php
$PHONE = $_POST['pass'];
mysql_connect('host.com', 'user', 'pass'); mysql_select_db('userdb');
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error()); while($row = mysql_fetch_assoc($results))
{ $rows[1] = $row; }
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]"
echo " you are logged in successfully"
?>
I get the result in log.php file in this form when value 'pass' is not being registered in database:
Welcome [//here user's first & last name if registered or remains blank] you are logged in successfully
I have table 'details' created
FNAME-First name
LNAME-Lastname
BIRTHDAY-Birthday
PHONE- user's no.
PASS- user's password.
My Question is , I want to just display ' You are not registered user' when pass value is not been registered in the database.Any help would be greatfull ?
Just check if you actually get a record or not using mysql_num_rows,
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PASS'",
mysql_real_escape_string($PASS))) or die(mysql_error());
if(mysql_num_rows($results) > 0){
while($row = mysql_fetch_assoc($results))
{
$rows[1] = $row;
}
echo "Welcome ";
echo $rows[1]['FNAME']." ".$rows[1]['LNAME'];
echo "You are logged in successfully";
}
else{
//Redirect them back with error message
header("Location: http://www.example.com/index.php?err='You are not registered user'");
}
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.
You took value in $phone variable for password and in select query used PASS= $PASS so how can it run?
Change this then run like below:
$results = mysql_query(sprintf("SELECT FNAME,LNAME FROM `details` WHERE PASS='$PHONE'",
mysql_real_escape_string($PHONE))) or die(mysql_error());
if(empty($rows[1][FNAME])){
echo 'You are not registered user';
}
else{
echo "Welcome ";
echo "$rows[1][FNAME]." ".$rows[1][LNAME]";
echo " you are logged in successfully";
}

Send hidden variables from one page to another

I have a Login script that is on my home page for my Login form that is also on my home page. When the user submits the form to Login he/she submits his/her username and password.
The database that the script accesses has the Username, Password, and Email Address stored from the users registration.
Once the user logs in successfully, he/she is redirected to a page that loads their previous "reviews" on the page which are stored within a different table within the same database.
I need to send the email from one table to the query on the redirected page.
Here is the code of my PHP code that processes the Login:
<?php
//If the user has submitted the form
if(isset($_REQUEST['username'])){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$password = protect($_POST['password']);
//Check if the username or password boxes were not filled in
if(!$username || !$password){
//if not display an error message
echo "<center>You need to fill in a <b>Username</b> and a <b>Password</b>!</center>";
}else{
//if they were continue checking
//select all rows from the table where the username matches the one entered by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none, display an error message
echo "<center>The <b>Username</b> you supplied does not exist!</center>";
}else{
//if there was a match continue checking
//select all rows where the username and password match the ones submitted by the user
$res = mysql_query("SELECT * FROM `users` WHERE `username` = '".$username."' AND `password` = '".$password."'");
$num = mysql_num_rows($res);
//check if there was no match
if($num == 0){
//if none display error message
echo "<center>The <b>Password</b> you supplied does not match the one for that username!</center>";
}else{
//if there was continue checking
//split all fields from the correct row into an associative array
$row = mysql_fetch_assoc($res);
//check to see if the user has not activated their account yet
if($row['active'] != 1){
//if not display error message
echo "<center>You have not yet <b>Activated</b> your account!</center>";
}else{
//if they have log them in
//set the login session storing there id - we use this to see if they are logged in or not
$_SESSION['uid'] = $row['id'];
//update the online field to 50 seconds into the future
$time = date('U')+50;
mysql_query("UPDATE `users` SET `online` = '".$time."' WHERE `id` = '".$_SESSION['uid']."'");
//redirect them to the usersonline page
echo 'REDIRECT';
}
}
}
}
exit;
}
?>
Here is the PHP Code that is on the Re-directed to page:
<?php
$con=mysqli_connect("","","","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM comments
WHERE email='$_POST[email]' ORDER BY dt");
while($row = mysqli_fetch_array($result))
{
echo $row['dt'] ." " . $row['email'] . " " . $row['body'];
echo "<br>";
echo "<br>";
}
?>
I need to add something to the first code to pick up the email address out of the table it uses to verify the Login information and send it to the second code to receive the "reviews." I have tried googling an answer and came up with nothing. Please help!
Since you have used the $_SESSION array in your code(which maybe is copied from somewhere), you can similarly store the email address in the same array.
$_SESSION['email'] = $row['email'];
In the later page, you'd need to replace $_POST['email'] with $_SESSION['email'].

Categories