cannot seem to define session data and echo it out - php

I am trying to setup $_SESSION data and echo it out onto the page. I am defining the sessions in the header
<?php
$users = $mysqli->query('SELECT * FROM fn WHERE username = '.$_SESSION['username']);
if (is_object($users)) {
if ($users->num_rows) {
while ($row = $users->fetch_assoc()) {
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$email = $row['email'];
$number = $row['number'];
$region = $row['region'];
$company = $row['company'];
$level = $row['level'];
}
}
}
$_SESSION['first_name'] = $first_name;
?>
I am then including the header.php file on my page and also using session_start();
I have no idea what im doing wrong.
I am managing to get the username and password to echo out... I assume its because it was added to the session upon login.

session_start() must come before you attempt to use $_SESSION variable, not after. Move your included file which contains session_start() to the top of that file for this to work.

You need to add session_start(). Put it after your PHP start tag

Related

php sessions not storing data

I'm currently having trouble with storing session data.
For some reason my sessions start and I can see it as a cookie but when I try to get my stored data from it it doesn't work.
Here is my code:
This is where I start the session and set the variables:
session_name("user");
session_start();
if ($groups != false) {
$_SESSION['groups'] = $groups->fetch_all(MYSQLI_ASSOC);
}
if ($dateformat != false) {
$_SESSION['dateformat'] = $dateformat;
}
$_SESSION['user_id'] = $row[0];
$_SESSION['user_firstname'] = $firstname;
$_SESSION['user_lastname'] = $lastname;
This is where I try to get my variables:
session_start();
if (isset($_SESSION['user_firstname'])) {
echo $_SESSION['user_firstname'];
}
Note: The page where I try to get the session data is my navbar/header it is only used with an php include statement.
It could be that $firstname is failing to be set. Try changing $_SESSION['user_firstname'] = $firstname; for example, to $_SESSION['user_firstname'] = "TEST"; and see if it stores that. If so, you're not giving $firstname a value.

Session Variable working in echo but not working in SQL query

I want to pass the value of login.php variables $user_key & $user_id to another file statusdata.php for which I have used session. In statusdata.php I want to use those session variable value in sql query of statusdata.php file.
To achieve this in login.php I pass the value of variable $user_key & $user_id to session variable $_SESSION["key"] & $_SESSION["id"] respectively then in statusdata.php I call session variable and pass their value in variable $user_key & $user_id of statusdata.php
Now the problem is when using the variable $user_key & $user_id in SQL query it is not returning proper output but using the same variable in echo it is giving proper value mean session is working fine when I echo the variable but not working in SQL. I have also tried passing the session variable directly but the same thing is happening to work in echo but not in SQL.
login.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = '8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED';
$user_id = '1997';
$mysql_qry = "select * from applications where application_key = '".$user_key."' and application_id like '".$user_id."';";
$result = mysqli_query($conn, $mysql_qry);
if (mysqli_num_rows($result) > 0){
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
echo "Login Success";
}
else {
echo "Login Not Success";
}
?>
statusdata.php
<?php
// Start the session
session_start();
require "conn.php";
$user_key = "-1";
if (isset($_SESSION["key"])) {
$user_key = $_SESSION["key"];
}
$user_id = "-1";
if (isset($_SESSION["id"])) {
$user_id = $_SESSION["id"];
}
//creating a query
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = '".$user_id."' AND applications.application_key = '".$user_key."';");
//executing the query
$stmt->execute();
//binding results to the query
$stmt->bind_result($id, $name, $aadhaar, $phone, $subject, $date, $description, $chairperson, $status, $officername, $officerremark, $lastupdate);
$applications = array();
//traversing through all the result
while($stmt->fetch()){
$temp = array();
$temp['applications.application_id'] = $id;
$temp['applications.applicant_name'] = $name;
$temp['applications.applicant_aadhaar'] = $aadhaar;
$temp['applications.applicant_phone'] = $phone;
$temp['applications.subject'] = $subject;
$temp['applications.date'] = $date;
$temp['applications.description'] = $description;
$temp['applications.chairperson_remark'] = $chairperson;
$temp['applications.status'] = $status;
$temp['officer_accounts.name_of_officer'] = $officername;
$temp['applications.officer_remark'] = $officerremark;
$temp['applications.last_update_on'] = $lastupdate;
array_push($applications, $temp);
}
//displaying the result in json format
echo json_encode($applications);
// Echo session variables that were set on previous page
echo "<br>key is " . $user_key . ".<br>";
echo "id is " . $user_id . ".";
?>
Output login.php
Login Success
Output statusdata.php
[]
key is .8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED..
id is .1997..
output I want from statusdata.php (I am getting it if I use direct value in variable $user_key & $user_id not session variable from login.php)
[{"applications.application_id":1997,"applications.applicant_name":"Tanishq","applications.applicant_aadhaar":"987654321","applications.applicant_phone":"123456789","applications.subject":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.date":"2018-07-02 09:11:47","applications.description":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.chairperson_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.status":1,"officer_accounts.name_of_officer":"Chayan Bansal","applications.officer_remark":"asdnjsnadnksncdnsjnvsavasdnjsnadnksncdnsjnvsav","applications.last_update_on":"2018-07-22 09:14:25"}]
key is 8C9333343C6C4222418EDB1D7C9F84D051610526085960A1732C7C3D763FFF64EC7F5220998434C896DDA243AE777D0FB213F36B9B19F7E4A244D5C993B8DFED.
id is 1997.
NOTE: I am taking the output of statusdata.php SQL query in JSON format as in the end I am extracting it in android.
Please help me I have tried everything which other similar questions are suggesting but nothing helps
Looks more like a typo situation. You have this in login.php:
$_SESSION["key"] = ".$user_key.";
$_SESSION["id"] = ".$user_id.";
Which is tainting your original values... by adding needless dots around them. Clean that up by simply assigning as so:
$_SESSION["key"] = $user_key;
$_SESSION["id"] = $user_id;
And it should begin working better.
Side note, you are using prepare, but not using bind_param. Change your SQL prepare to the following (note the ? placeholders), and add bind_param:
$stmt = $conn->prepare("SELECT applications.application_id, applications.applicant_name, applications.applicant_aadhaar, applications.applicant_phone, applications.subject, applications.date, applications.description, applications.chairperson_remark, applications.status, officer_accounts.name_of_officer, applications.officer_remark, applications.last_update_on
FROM applications INNER JOIN officer_accounts ON applications.account_id = officer_accounts.account_id
WHERE applications.application_id = ? AND applications.application_key = ?;");
$stmt->bind_param('ss',$user_id,$user_key);

PHP/MYSQL - How do i assign data fetched from the database(stored in variables) to a session variable?

I am having a bit of an issue passing array variables that are fetched from the database and stored in variables and passing them into session variables to use all over the site.
Code:
$rid=$_SESSION['SESS_MEMBER_ID'] ;
$recquery = 'SELECT * FROM clinic_receptionist,clinic_table where clinic_receptionist.recep_clinic_id = clinic_table.ID AND recep_id ='.$rid;
$recresult = mysqli_query($conn,$recquery);
if(mysqli_num_rows($recresult)>0)
{
while($row = mysqli_fetch_assoc($recresult))
{
$cid = $row['clinic_id'];
$cname = $row['clinic_name'];
$name = $row['recep_full_name'];
$phone = $row['recep_mobile'];
$email = $row['recep_email'];
$address = $row['recep_address'];
$gender = explode(",",$row['recep_gender']);
$dob = $row['recep_dob'];
$doj = $row['recep_doj'];
}
}
?>
The above code is where the select query is happening. I wanted to know how do I assign $cid and $cname to a $_SESSION variable in different pages. Any help would be much appreciated. Thanks
CODE:
<?php session_start();
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = mysqli_query($conn,$appquery);
if(mysqli_num_rows($appresult)>0)
{
while($row = mysqli_fetch_array($appresult))
{
$_SESSION['cid'] = $row['ID'];
$_SESSION['cname'] = $row['clinic_name'];
$ptdate = $row['date'];
$pttime = $row['time'];
$ptname = $row['pt_name'];
$ptphone = $row['pt_ph_num'];
$ptemail = $row['pt_email_id'];
}
}
?>
The above code is the place from where I want to receive the id and clinic name.
<?php
// Start the session
session_start();
//Assigning the values to $_SESSION
$_SESSION['cid'] = $row['clinic_id'];
$_SESSION['cname'] = $row['clinic_name'];;
?>
session_start
You need to call session_start() on each page to initialize the session, of course; after that you can just
$_SESSION['cid'] = $cid;
$_SESSION['cname'] = $cname;
to store those values in $_SESSION.
By the way, someone's going to tell you to use a prepared statement for that query, so it might as well be me.
Perhaps an illustration is in order.
page1.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
$appquery = 'SELECT * FROM appointment_table,clinic_table where clinic_table.ID = appointment_table.clinic_id';
$appresult = $conn->query($appquery);
if(($rowcount = $appresult->num_rows()) > 0)
{
// create arrays to pass data
$cids = array($rowcount);
$cnames = array($rowcount);
$i = 0;
while($row = $appresult->fetch_array())
{
// add values to arrays
$cids[$i] = $row['ID'];
$cnames[$i] = $row['clinic_name'];
$i++;
}
// add arrays to session
$_SESSION['cids'] = $cids;
$_SESSION['cnames'] = $cnames;
}
page2.php:
<?php
session_start(); // find session, or create new one
include('header.php');
include('menu.php');
include('config.php');
// retrieve arrays from session
$cnames = $_SESSION['cnames'];
$cids = $_SESSION['cids'];
// ... and print them
$count = count($cids);
for ($i = 0; $i < $count; $i++)
{
echo "cid = " . $cid[$i] . "; cname = " . $cname[$i] . "<br>";
}
page1.php performs the query and stores cid and cname values in arrays which are then stored in $_SESSION. page2.php retrieves the arrays from $_SESSION and echoes them out. In production, of course, it would be considered more efficient to run the query on the page where it is displayed, and only pass key values between pages.
I've also used object syntax instead of procedural syntax for mysqli, just to show what it looks like. As usual, I leave error handling as an exercise for the reader.

Session variable does not persist

I can't seem to get my session variable to output. It works fine on the other one I'm using:
$_SESSION['status']['register']['username'] = $username;
header('Location: register-form.php');
When you are taken to register-form.php it should output the variable for you:
<?php
if(isset($_SESSION['status']['register']['username'])){
$username = $_SESSION['status']['register']['username'];
} else {
$username = '';
}
?>
Exact same code is used on email_address and works fine.
Here is the same code for the email
$_SESSION['status']['register']['email_address'] = $email_address;
And on the form page:
<?php
if(isset($_SESSION['status']['register']['email_address'])){
$ea_value = $_SESSION['status']['register']['email_address'];
} else {
$ea_value = '';
}
?>
You miss to initialize your session with
session_start();
at top of your register_form.php

PHP/MYSQL echo logged in user's data from database table

can anyone help me with the situation I'm in. I've been trying to find answers on how to display a user's first name, last name email...etc from the table that has the info stored but my only luck with echoing this info is only getting either ALL the info for a certain feel to show like all emails instead of just 1 specific email for the user or I just end up with mysql errors.
here's my index.php source
<?php
session_start();
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$email = $_SESSION['email'];
$firstname = $_SESSION['first_name'];
$lastname = $_SESSION['last_name'];
$businessname = $_SESSION['company_name'];
$country = $_SESSION['country'];
$plan = $_SESSION['plan'];
} else {
header("Location: http://somewebsite.com");
}
include 'connect.php';
$first_name = $_GET['first_name'];
$last_name = $_GET['last_name'];
?>
for instance I would like to echo the user's first name in the header
<span class="username">USER</span> <--replace user with logged in user's firstname n last name-->
You can do something like this:
Write a function to fetch specific data from the table such as one below.
function getuserfield($field) {
$query = "SELECT $field FROM users WHERE id='".$userid."'";
if ($query_run = mysqli_query($query)) {
if ($query_result = mysqli_result($query_run, 0, $field)) {
return $query_result;
}
}
}
/* userid = $_SESSION['id']; */
The "$query_result" will display the username. $field is the specific field you want to display. By this function you can fetch any particular data from the specified field

Categories