Reputation: 195
I'm really new to programming in PHP so the problem I'm having may be an extremely simple one to solve but I cant find the solution online and I've tried a number of different methods myself so any help you can give me would be really appreciated. The problem I'm having is that when a user logs in to the system I need their username to be stored in a variable which can be used when a different PHP script is called. For instance, when the user first logs in to the system, the username they have entered is fetched using code similar to that seen below:
$username = ($_POST['entered_username']);
mysql_real_escape_string($username);
Where 'entered_username' is the name of the username input in the log in form within the HTML code. The problem I'm having is how to store the $username variable so it can be used in a different script. For instance when the user moves onto a page where he/she can see their own personal information which is stored in a MySQL database. Ideally I would like to use a SQL query such as the one below:
$qry = ("select Username, Password, UserType from $table where Username = '".$username."'");
However this is not possible as the variable $username would not be defined in this script. So how can I store the $username variable in order to access it again via another PHP script. Thanks in advance for all your help and apologies if any of the information I have provided is too vague.
Upvotes: 3
Views: 1136
Reputation: 4409
Most simple solution: SESSION
variables.
On your login page, add this code at the top of the page:
session_start();
then set your variables like this:
$_SESSION['var_1'] = $some_val;
$_SESSION['var_2'] = $some_other_val;
you can then access them on any other php page with the session_start();
code on top.
Note however that this session data gets deleted when the user closes his/her browser. For more persistant, "long-lived" variables use $_COOKIE
variables or store values in db and access the variables from there.
Upvotes: 1
Reputation: 17
Use $_SESSION variables. When a user logs in to your site store the variable in $_SESSION global variable.
session_start();
$_SESSION['user'] = $/* user */;
In another php script you can set ;
session_start();
$user = $_SESSION['user'];
Upvotes: 0
Reputation: 10447
You need to use the $_SESSION
variable. It allows you to pass data between pages.
session_start();
$username = ($_POST['entered_username']);
mysql_real_escape_string($username);
$_SESSION['username'] = $username;
then on any other page you can call it by using:
session_start();
$qry = ("select Username, Password, UserType from $table where Username = '".$_SESSION['username']."'");
Make sure that you call session_start()
at the top of your page, before you have outputted any HTML to the page. Otherwise you will cause a headers error.
Upvotes: 0