Retrieving and displaying logged in info in PHP - php

I'm trying to retrieve my logged in user data to no avail. Please check my
enter code here private function getUserData($user_name)
{
// if database connection opened
if ($this->databaseConnection()) {
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare("SELECT * FROM users WHERE user_name='$_SESSION['user_name']'");
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
return $query_user->fetchObject();
} else {
return false;
}
}

Got the way to move about it ,Thanks #ADyson for the response and follow up
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>YOUR ORDER , We will contact you in a few !!!!</title>
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<link href="assets/css/main.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php include 'header.php'; ?>
<section>
<div class="container">
<strong class="title">MY ORDERS</strong>
</div>
<div class="profile-box box-left">
<?php
require('db.php');
// SQL query
$strSQL = "SELECT user_name, phone, firstname, lastname, service, referal,user_registration_datetime FROM users WHERE user_name = '".$_SESSION['user_name']."'";
// 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)) {
echo WORDING_PROFILE_PICTURE . '<br/>' . $login->user_gravatar_image_tag;
echo "<div class='info'> <strong>NAME:</strong> <span>".$row['firstname'].", ".$row['lastname']."</span></div>";
echo "<div class='info'><strong>phone No:</strong> <span>".$row['phone']."</span></div>";
echo "<div class='info'><strong>SERVICE:</strong> <span>".$row['service']."</span></div>";
echo "<div class='info'><strong>REFERAL:</strong> <span>".$row['referal']."</span></div>";
echo "<div class='info'><strong>DATE QUERIED:</strong> <span>".$row['user_registration_datetime']."</span></div>";
}
// Close the database connection
mysqli_close($myConnection);
?>
<div class="options">
<a class="btn btn-primary" href="editprofile.php">Edit Profile</a>
<a class="btn btn-success" href="changepassword.php">Change Password</a>
</div>
</div>
</section>
<script src="assets/js/jquery-3.1.1.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>

Related

Display output of MySQL query on button badge

I am new to php mysql & have this query where i want to display the output of mysql query on button badge. I have tried the following code
Kindly help .
<?php
$con=mysqli_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysqli_select_db($con,"sales");
$sth = mysqli_query($con,"select sum(sal) as Salary from `sales` ");
$result = mysqli_query($con,$sth);
$row = mysqli_fetch_assoc($con,$result);
echo $row;
?>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<button type="button" class="btn btn-primary">Primary <span class="badge"><?php echo $row; ?></span></button>
</body>
</html>
<?php echo ''.$row['Salary'].''; ?>
As long as you have verified the settings and the query is correct the above line should output what you are looking for.
EDIT
<?php
$con=mysqli_connect("localhost","root","") or die("Failed to connect with database!!!!");
mysqli_select_db($con,"sales");
$sth = "select sum(sal) as Salary from `sales` ";
$result = mysqli_query($con,$sth);
$row = mysqli_fetch_assoc($result);
Try That

Session Variables in Datatables Plugin

I am creating a PHP/MySQL based application and it need to be able to carry over session variables into the DataTable plugin I use on a page in my app. The application is rather complicated, so I will explain how it works before I ask specific questions.
On index.php, there is a dropdown menu that shows the departments that use this application within my organization. The department list is generated by a mySQL table that has their department name and department code. The $dept variable stores the department code value from the selected option in the dropdown menu on submit. In turn, the $_SESSION["department"] variable stores $dept and redirects to the checkin page if successful.
<?php
require_once('connection.php');
session_start();
if (isset($_POST['submit']))
{
$dept = $_POST['dept'];
$_SESSION["department"] = $dept;
header("Location: checkin.php");
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
</ul>
</div>
<div class="top-bar-right">
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<h2>Visitor Management</h2>
<br/>
<form id="dept" method="post" name="dept">
<?php
echo "<select name='dept'>";
echo '<option>'.'Please select a department'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM departments");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['code']."'>".$row['name']
.'</option>';
}
echo '</select>';
?>
<input type="submit" class="button" value="Submit" name="submit">
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The session variable is then carried throughout the site and is used to determine which table needs to be shown. For instance, in checkin.php, we need to display staff members in a dropdown list. We have multiple tables based on the departments using the application. One table we have is called ts_staff If the session variable is stored as the string ts, we do the following steps to make sure the app is connecting to the right database:
We store the session variable from index.php into a global variable on checkin.php $dept = $_SESSION[department];
We create another new variable to concatenate the global variable and the _staff string which is used in all our mySQL staff tables: $staffTable = $dept . "_staff";
Lastly, we use the $staffTable variable as the database table that needs to be displayed: $query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
Here's the full checkin.php code:
<?php
// connect to database
require_once('connection.php');
session_start();
//get session variable, if empty, unset and logout
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
//submit values on submit
if (isset($_POST['submit']))
{
// store form data values
$suid = mysqli_real_escape_string($VisitorManagement, $_POST['suid']);
$staff = mysqli_real_escape_string($VisitorManagement, $_POST['staff']);
$checkinTable = $dept . "_checkin";
// insert varaibles into table rows
$sql = "INSERT INTO {$checkinTable} (suid, staffMember) VALUES ('$suid', '$staff')";
// check if row was inserted correctly
if (mysqli_query($VisitorManagement, $sql)) {
header('Location: thank-you.php');
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($VisitorManagement);
}
}
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="css/foundation.min.css" />
<link rel="stylesheet" href="css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
</head>
<body>
<!-- nav -->
<div class="top-bar">
<div class="top-bar-left">
<ul class="menu">
<li>Check-In</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Admin Login</li>
<li>Logout</li>
</ul>
</div>
</div>
<div class="row text-center" style="margin-top: 5%;">
<h1>Syracuse University</h1>
<!-- replace with whatever department they select -->
<h2>Technical Services</h2>
</div>
<div class="row">
<form id="checkin" method="post" name="checkin">
<div class="row">
<div class="medium-12 columns">
<label>Please Swipe Your SUID Card
<input type="text" placeholder="SUID Number Here" id="suid" name="suid" required>
</label>
</div>
<div class="medium-12 columns">
<label>Who Are You Here to See?
<?php
$staffTable = $dept . "_staff";
echo "<select name='staff'>";
echo '<option value="">'.'Please select a staff member'.'</option>';
$query = mysqli_query($VisitorManagement, "SELECT * FROM {$staffTable}");
while($row=mysqli_fetch_array($query))
{
echo "<option value='". $row['fullName']."'>".$row['fullName']
.'</option>';
}
echo '</select>';
// close connection
mysqli_close($VisitorManagement);
?>
</label>
</div>
<div class="medium-12 columns">
<input type="submit" class="button" value="Submit" name="submit">
</div>
</div>
</form>
</div>
<script src="js/vendor/jquery.min.js"></script>
<script src="js/vendor/what-input.min.js"></script>
<script src="js/foundation.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
The problem is that on reports.php, I am using the DataTables plugin to dynamically organize and filter a table, but I need to be able to carry the session variable over into the plugin so it knows to organize the specific table based on what the user selected on the index.php screen.
reports.php just calls DataTables and using another page, response.php to turn the data from the table into JSON to be displayed. Here's reports.php:
<?php session_start();
if(empty($_SESSION['department'])) {
session_unset();
session_destroy();
header("Location: index.php");
} else {
$dept = $_SESSION[department];
}
$checkinTable = $dept . "_checkin";
?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Visitor Management</title>
<link rel="stylesheet" href="../css/foundation.min.css" />
<link rel="stylesheet" href="../css/app.css" />
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/24365087-b739-4314-af6e-741946b60bef.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/b05259d9-ca62-44a8-8a19-d3facdbd64df.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/2603d516-f938-4b52-ae3a-11d25bb4c555.css"/>
<link type="text/css" rel="stylesheet" href="http://fast.fonts.net/cssapi/510266cf-74ab-4fa8-9b39-dd37b90d6ab0.css"/>
<link type="text/css" rel="stylesheet" href="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.css"/>
</head>
<body>
<?php
if (!isset($_SESSION['user'])) {
header("Location: ../login.php"); // If session is not set that redirect to Login Page
}
?>
<div class="top-bar admin">
<div class="top-bar-left">
<ul class="menu">
<li class="menu-text">Visitor Management</li>
</ul>
</div>
<div class="top-bar-right">
<ul class="menu">
<li>Logout</li>
<li>Help</li>
</ul>
</div>
</div>
<div class="medium-2 columns dash">
<ul>
<li>Dashboard</li>
<li>Staff</li>
<li class="active">Reports</li>
</ul>
</div>
<div class="medium-10 columns">
<div class="row checkin">
<h2>Reports</h2>
<table class="checkin" id="checkin">
<thead>
<tr>
<th>ID</th>
<th>SUID #</th>
<th>Staff Member</th>
<th>Student Name</th>
<th>Student Email</th>
<th>Check In Date/Time</th>
</tr>
</thead>
</table>
<!--<div class="float-left">
Export to Excel
</div>
<div class="float-right">
</div>-->
</div>
</div>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"></script>
<script src="../js/vendor/what-input.min.js"></script>
<script src="../js/foundation.min.js"></script>
<script src="../js/app.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/r/dt/jq-2.1.4,jszip-2.5.0,pdfmake-0.1.18,dt-1.10.9,af-2.0.0,b-1.0.3,b-colvis-1.0.3,b-html5-1.0.3,b-print-1.0.3,se-1.0.1/datatables.min.js"></script>
<script>
$(document).ready(function() {
$('#checkin').DataTable({
"bProcessing": true,
"serverSide": false,
"dom": 'lBfrtip',
"buttons": [
{
extend: 'collection',
text: 'Export',
buttons: [
'copy',
'excel',
'csv',
'pdf',
'print'
]
}
],
"ajax":{
url :"response.php", // json datasource
type: "post", // type of method ,GET/POST/DELETE
data: {}
}
});
});
</script>
</body>
</html>
Here's response.php:
<?php
//include connection file
include_once("../connection.php");
// initilize all variable
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
//define index of column
$columns = array(
0 => 'id',
1 => 'suid',
2 => 'staffMember',
3 => 'studentName',
4 => 'studentEmail',
5 => 'checkinDateTime'
);
$where = $sqlTot = $sqlRec = "";
// check search value exist
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( studentName LIKE '".$params['search']['value']."%' ";
$where .=" OR staffMember LIKE '".$params['search']['value']."%' ";
$where .=" OR studentEmail LIKE '".$params['search']['value']."%' ";
$where .=" OR suid LIKE '".$params['search']['value']."%' ";
$where .=" OR checkinDate LIKE '".$params['search']['value']."%' )";
}
// getting total number records without any search
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";
$sqlTot .= $sql;
$sqlRec .= $sql;
//concatenate search sql if value exist
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
//$sqlRec .= " ORDER BY ". $columns[$params['order'][0]['column']]." ".$params['order'][0]['dir']." LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($VisitorManagement, $sqlTot) or die("database error:". mysqli_error($VisitorManagement));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($VisitorManagement, $sqlRec) or die("error to fetch check-in data");
//iterate on results row and create new index array of data
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
In response.php, I need to able to replace ts_checkin, which is shown on this line:
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM `ts_checkin`";`
with a variable called $checkinTable that would concatenate similar to how checkin.php does with the staff table. So essentially I would like to have $checkinTable = $dept . "_checkin" with $dept equaling the value of the session variable.
When I go to do this, I get this error from DataTables: DataTables warning: table id=checkin - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
Is it possible to get this working? I would like to keep DataTables as its the best way to achieve on-the-fly table filtering, searching, and sorting (plus it's a highly requested feature by our departments). But I need to be able to set the table based on the session variable.
I apologize for the length of this question. If there needs to be clarification, let me know.
I'm not certain to understand the question...
Are you saying this is not working ?
Did you try it written like this?
(notice the space after FROM. It is necessary!)
$checkinTable = $dept . "_checkin";
$sql = "SELECT id, suid, staffMember, studentName, studentEmail, date_format(checkinDateTime, '%b %d, %Y, %h:%i %p') as checkinDateTime FROM " . $checkinTable;
For sure, $dept has also to be defined.
And the resulting $checkinTable has to be an existing table name.
Ok...
This looks to be missing in your response.php:
session_start();
$dept = $_SESSION[department];
$checkinTable = $dept . "_checkin";

$_SESSION in PHP is always returning 1

I'm trying to develop a login system in PHP which has faculty_login.php which displays faculty_login_option.inc.php which has a login form and if $_SESSION['f_id'] is set it redirects to faculty_upload_option.php. where faculty details are fetched from faculty_table using $f_id = $_SESSION['f_id'] as the primary key.but $_SESSION['f_id'] is always returning 1 and user is logging in as the user whose f_id is 1.
<?php
//faculty login page.faculty_login.php
//if logged in show upload option/show login option.
require_once 'resources/core.inc.php';//session is set here
require_once 'resources/connect.inc.php';//init db connection
if(isset($_SESSION['f_id'])&&!empty($_SESSION['f_id'])){
require_once 'faculty_upload_option.inc.php';
}
else{
require_once 'faculty_login_option.inc.php';
}
?>
<?php
/* faculty_login_db.php
* Check if the faculty can login or the credentials are wrong.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_POST['f_username'])&&isset($_POST['f_password'])){
if(!empty($_POST['f_username'])&&!empty($_POST['f_password'])){
$username = stripcslashes($_POST['f_username']);
$password = stripcslashes($_POST['f_password']);
$result = $conn->prepare("SELECT f_id FROM faculty_table WHERE f_username= :hjhjhjh AND f_password= :asas");
$result->bindParam(':hjhjhjh', $username);
$result->bindParam(':asas', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($result->rowCount() == 1) {
$_SESSION['f_id'] = $rows ;
$_SESSION['f_username'] = $username;
header('Location:faculty_login.php');
}
else{
header('Location:faculty_login.php?username='.$username);
}
}
else{
header('Location:faculty_login.php');
}
}
else{
header('Location:faculty_login.php');
}
?>
<?php
/* faculty_login_option.php
* faculty login page. check if user exists/ use faculty_login_db.php
*/
?>
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Home</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link rel="stylesheet" href="resources/loginstyle.css">
</head>
<body>
<?php
//<img alt="full screen background image" src="images/orange.jpg" id="full-screen-background-image" />
?>
<div id="back">Home</div>
<div id="header">
<h3>FACULTY LOGIN</h3><br>
</div>
<hr>
<div id="container">
<center>
<form action="faculty_login_db.php" method="post">
<input type="text" onFocus="if(this.value=='Username'){this.value=''}" name="f_username" class="buttons" value="<?php
if(isset($_GET['username']))
{
echo $_GET['username'];
}else{echo 'Username';}
?>"><br>
<input type="password" onFocus="if(this.value=='Password'){this.value='';}" name="f_password" class="buttons" value="Password"><br>
<input type="submit" value="Login" class="lbutton">
</form>
</center>
<?php
if(isset($_GET['username'])){
?>
<div id="errormsg">Username or password is invalid.</div>
<?php
}
?>
</body>
<?php
/* this is faculty_upload_option.inc.php
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
require_once 'resources/core.inc.php';
require_once 'resources/connect.inc.php';
if(isset($_SESSION['f_id'])&&isset($_SESSION['f_username'])&&!empty($_SESSION['f_id'])){
$f_id=trim(isset($_SESSION['f_id']));
if(!empty($f_id)){
$result = $conn->prepare("SELECT * FROM faculty_table WHERE f_id=:id");
$result->bindparam(':id', $f_id);
$result->execute();
$rows = $result->fetchAll();
foreach($rows as $db_rows){
$f_username = $db_rows['f_username'];
$category = $db_rows['category'];
$branch = $db_rows['branch'];
}
//page which should be displayed if user logs in.?>
<html>
<head><title><?php echo $f_username; ?></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0 , maximum-scale=1">
<link href='http://fonts.googleapis.com/css?family=Indie+Flower|Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="resources/upload_style.css">
</head>
<body><div id="parent">
<div id="header">
<img src="images/no-profile-image.png" width="30%" id="noimg">
<span id="addfont"><h1><?php echo $f_username;?></h1></span>
<h2><?php echo $category;?></h2>
<p><?php echo $branch;?></p>
<center><div class="buttons" id="left">Home</div><div class="buttons" id="right">Logout</div></center>
</div>
Are you destroying session correctly on logout? Are you setting session id before hitting the condition somewhere? What is the value before hitting the comparion condition?

Custom PHP Function works except on one specific page

Can someone please help me understand why the below function works in option.php but does not work in main.php? From what I'm seeing, it looks as if the query is not going through when the function is called on main.php; however, it clearly goes through on option.php.
custom_functions.php
function fetch_options(){
global $connection;
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo "<option value=\"{$row['a']}\">{$row['b']}</option>";
}
mysqli_free_result($result);
mysqli_close($connection);
}
option.php
<?php
require_once('lib/db.php');
require_once('lib/custom_functions.php');
echo "<select><option value=\"0\">Unknown</option>";
fetch_options();
echo "</select>";
?>
main.php
<?php
require_once('lib/db.php');
require_once('lib/custom_functions.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Main</title>
<link href="css/bootstrap.css" rel="stylesheet">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<?php include('lib/nav.php'); ?>
<div class="container-fluid">
<div class="row">
<div class="col-lg-2" style="padding:none;background-color:#ccc;min-height: calc(100vh - 52px);">
</div>
<div class="col-lg-10" style="padding:none;" id="page2">
<select class="form-control" id="e_CR" name="craft">
<option value="0">Unknown</option>
<?php fetch_options(); ?>
</select>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="js/validate.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jfunctions.js"></script>
</body>
</html>
The included nav.php file contained a mysqli_close call and terminated the connection before the fetch_options() function was run.

PHP echo to another page

What i wrong with this code below. I am trying to get it to echo to another page but it does not seem to pick up the data that is on the database.
<?php
{
// connect to server
mysql_connect("localhost", "u", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
//Create a query that selects all data from the PATIENT table where the username and password match
$query = "SELECT`Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
$row=mysql_fetch_array($result);
$_SESSION['Appointment_id'] = $row['Appointment_id'];
$_SESSION['Doctor_id'] = $row['Doctor_id'];
}
}
?>
Appointment.php
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
</div>
<div data-role="content">
<?php
{
// connect to server
mysql_connect("localhost", "", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
$row=mysql_fetch_array($result);
$_SESSION['Appointment_id'] = $row['Appointment_id'];
$_SESSION['Doctor_id'] = $row['Doctor_id'];
}
}
?>
</div>
</div>
</body>
</html>
Echo onto this page
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Details
</h3>
</div>
<div data-role="content">
<form name="form1" method="post" action="login.php">
<strong>Your Details</strong>
<br />
<br />
Appointment: <?php echo $_SESSION['Appointment_id'];?>
<br />
<br />
Doctor: <?php echo $_SESSION['Doctor_id'];?>
<br />
<br />
</div>
</div>
</body>
</html>
The second section is where the database is picking up the information (Appointment) and the third shows where i need it to display
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta http-equiv="refresh" content="2;url=details1.php">
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Login Process
</h3>
</div>
<div data-role="content">
login.php
<!DOCTYPE html>
<?php
session_start();
?>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta http-equiv="refresh" content="2;url=details1.php">
<title>
</title>
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="my.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.mobile/1.2.0/jquery.mobile-1.2.0.min.js">
</script>
<script src="my.js">
</script>
<!-- User-generated css -->
<style>
</style>
<!-- User-generated js -->
<script>
try {
$(function() {
});
} catch (error) {
console.error("Your javascript has an error: " + error);
}
</script>
</head>
<body>
<!-- Home -->
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
<a data-role="button" data-theme="d" href="login.html" data-icon="arrow-l" data-iconpos="left" class="ui-btn-left">
Back
</a>
<a data-role="button" href="index.html" data-icon="home" data-iconpos="right" data-theme="d"class="ui-btn-right">
Home
</a>
<h3>
Login Process
</h3>
</div>
<div data-role="content">
<?php
// takes the variables from action script and assigns them php variables names
$user = $_POST ['username'];
$pass = $_POST ['password'];
// if there is a user name and password
if ($user && $pass)
{
// connect to server
mysql_connect("localhost", "", "") or die(mysql_error());
//select database
mysql_select_db("") or die(mysql_error());
//Create a query that selects all data from the PATIENT table where the username and password match
$query = "SELECT * FROM Patient WHERE Username = '$user' AND Password = '$pass'";
//executes query on the database
$result = mysql_query ($query) or die ("didn't query");
//this selects the results as rows
$num = mysql_num_rows ($result);
//if there is only 1 result returned than the data is ok
if ($num == 1)
{
//sends back a data of "Success"
echo "Successful Login";
$row=mysql_fetch_array($result);
$_SESSION['Title'] = $row['Title'];
$_SESSION['First_name'] = $row['First_name'];
$_SESSION['Last_name'] = $row['Last_name'];
$_SESSION['Address'] = $row['Address'];
$_SESSION['Line_2'] = $row['Line_2'];
$_SESSION['Line_3'] = $row['Line_3'];
$_SESSION['Postcode'] = $row['Postcode'];
$_SESSION['Home'] = $row['Home'];
$_SESSION['Mobile'] = $row['Mobile'];
}
else
{
//sends back a message of "failed"
echo "Unsuccessful Login";
}
}
?>
</div>
</div>
</body>
</html>
please add at the top
session_start();
since you are using $_SESSION .. you need to use session_start() immediately after php opening tag
<?php
session_start();
and not only on this page .. session_start() should be there on every page where you want you use session_start() .. otherwise $_SESSION is not accessible..
Please use session_start() on both of the pages, if you dont start that you will not be able to use that
EDIT
Create a test page to see your sessions are working?
if yes then test that on other page
also try adding a simple echo in your if condition where you are setting the session values. If that echo triggers it means your code is correct and something is wrong with SESSION. And if echo dont trigger, it means your code is not correct and sessions are not being set
if your just trying to get the first row
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment` WHERE rownum = 1 ; ";
Edit:
Ok so here I believe the logical error lies
$query = "SELECT `Appointment_id`, `Doctor_id`, `Patient_id`, `Appointment_time`, `Appointment_date` FROM `Appointment`";
$result = mysql_query ($query) or die ("didn't query");
$num = mysql_num_rows ($result);
if ($num == 1)
{
}
Since your query has no WHERE clause, it is returning all records that there are, and You are setting the SESSION values only when there is 1 record. You should also have an else condition to see what happens in real.
Create a query that selects all data from the PATIENT table where the username and password match
But your query does not do that, it gets data for all the PATIENTs
For example if your username and password came from a POSTed form then you could do
$username=mysql_real_escape_string($_POST["username"]);
$password=mysql_real_escape_string($_POST["password"]);
Then you could use both those values inside a WHERE clause. Since I do not know the structure of your tables apart from just reading your query, I can not write it exactly. But just to give you an idea, a where could be like
$query="SELECT id from YourTable where $username='$username' and password='$password'"
Very important to note since you are a beginner : mysql_* functions should no longer be used. If you are starting, don't start with something that's gone. Read about mysqli_* or PDO
Edit 2:
Ok great, so do this
On successful login where you store Patient's details in SESSION, also store Patient_id like $_SESSION['Patient_id'] = $row['Patient_id']; //or maybe its just id. Check your table
On Appointment.php change your query to
$pid=intval($_SESSION["Patient_id"]);
$query = "SELECT Appointment_id, Doctor_id, Patient_id, Appointment_time, Appointment_date FROM Appointment where Patient_id=$pid";
Add an else condition below your if($num==1) { } block like
PHP
else{
echo "Somehow we didn't get 1 record";
die();
}

Categories