PHP Session working on Desktop not on Mobile - php

I'm trying to create a mobile site and I'm using sessions to get the users username. When I view the mobile site on my desktop it works fine and I can get the username of the user from page to page. But when I view the same site on my mobile browser the session doesn't carry over from page to page.
Here is my login page:
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***info to connect to database) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<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" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="//netdna.bootstrapcdn.com/font-awesome/3.2.0/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN LOGIN PAGE -->
<div data-role="page" id="login" style="background: #c66200;">
<div data-role="header">
</div>
<div data-role="content">
<center>
<div class="ui-grid-b">
<img src="images/logo_white.png">
</div>
</center>
<?
//check if the login session does no exist
if(strcmp($_SESSION['uid'],'') == 1){
//if it doesn't display an error message
header('Location: feed.php');
}
else {
//If the user has submitted the form
if($_POST['submit']){
//protect the posted value then store them to variables
$username = protect($_POST['username']);
$thepassword = md5($_POST['password']);
$password = protect($thepassword);
//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 the 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 not a match
if($num == 0){
//if not 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 not a match
if($num == 0){
//if not 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 fom 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'];
//show message
echo "<center>You have successfully logged in!</center>";
//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
$loginpage="#feed";
header("Location: feed.php" . $loginpage);
exit();
}
}
}
}
}
}
?>
<center>
<form action="index.php#feed" method="post" data-ajax="false">
<div style="width: 75%; border-top: 1px solid #ffffff; margin-top: 20px; padding-top: 20px; border-bottom: 1px solid #ffffff; margin-bottom: 20px; padding-bottom: 20px;">
<div class="ui-hide-label">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="" placeholder="username" data-mini="true" style="color: #c66200;"/><br>
<label for="password">password:</label>
<input type="password" name="password" id="password" value="" placeholder="password" data-mini="true" style="color: #c66200;"/><br>
</div>
<div style="width: 40%;">
<input type="submit" data-role="button" name="submit" value="Login" data-mini="true" style="color: #c66200 !important;"/>
</div>
</div>
</center>
<?
ob_end_flush();
?>
</div>
<div data-role="footer">
</div>
</div>
<!-- END LOGIN PAGE -->
</body>
</html>
Here is what I have for my feed.php page which the login page routes to. I can get the users info on this page. Whenever I click a link to go to the "browseresults" page the information doesn't carry over.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***db info***) or die(mysql_error());
$db = mysql_select_db('dbname', $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<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" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 3 -->
<div data-role="page" id="browse">
<div data-role="panel" id="settingspanel" data-position="left" data-display="overlay">
<ul data-role="controlgroup">
<li>Page Two</li>
<li>Page Three</li>
<li>Page Four</li>
<li>Logout</li>
</ul>
</div>
<div data-role="header" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="padding-top: 5px; border-bottom: 1px solid #eccfb3; padding-bottom: 5px;">
<center><img src="images/logo_app_white.png" width="30px"></center>
</div>
<div data-role="content">
<?php
$fquery = "SELECT state, city, count(city) as num FROM needs WHERE country='$usercountry' AND status='posted' GROUP BY state, city ORDER BY state, city";
if ($result = mysql_query($fquery)) {
$num_rows = mysql_num_rows($result);
echo "<table>";
$i = 1;
$cols = 2;
$prev = "";
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
echo "<tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr><th align='left'>$fstate</th></tr><tr>";
}
echo "<td><a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a> </td>";
echo ($i < $num_rows) ? ((($i % $cols) == 0) ? '</tr>' : '') : '';
$i++;
$prev = $fstate;
}
echo "</table>";
}
?>
</div>
<div data-role="footer" data-position="fixed" data-theme="c" data-tap-toggle="false" data-id="foo1" style="border-top: 1px solid #eccfb3; padding-top: 5px;">
<div data-role="navbar" style="background: #ce8339;">
<ul>
<li>My Feed</li>
<li>Submit</li>
<li>Browse</li>
<li>Projects</li>
</ul>
</div><!-- /navbar -->
</div>
</div>
<!-- END PAGE 3 -->
</body>
</html>
And here is the browseresults.php page which is the page that is not getting the session data.
<?php
//allow sessions to be passed so we can see if the user is logged in
session_start();
ob_start();
//connect to the database so we can check, edit, or insert data to our users table
$con = mysql_connect(***dbinfo***) or die(mysql_error());
$db = mysql_select_db(dbname, $con) or die(mysql_error());
//include out functions file giving us access to the protect() function made earlier
include "./functions.php";
$userid = $_SESSION['uid'];
$lookupusername = mysql_query("SELECT * FROM users WHERE ID='$userid'");
$row = mysql_fetch_assoc($lookupusername);
$username = $row['username'];
$usercountry = $row['country'];
?>
<!DOCTYPE html>
<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" />
<title>15:11 Project Mobile</title>
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<link href="font-awesome/css/font-awesome.css" rel="stylesheet">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
</head>
<body>
<!-- BEGIN PAGE 1 -->
<?
echo "$username";
?>
<!-- END PAGE 1 -->
</body>
</html>
no username is outputted. Can anyone help explain why and help me get this sorted out please?

Related

I am trying to create a resume registry using php PDO prepared statement

I am trying to insert form data to my profile table when I click the add button, but whenever I test my code below it just reloads my add.php page and clears the form instead of adding it to my table.
add.php code:
<?php
//connection to the database
$pdo = require_once 'pdo.php';
session_start();
//if user is not logged in redirect back to index.php with an error message
if(!isset($_SESSION['user_id'])){
die("ACCESS DENIED");
return;
}
//if the user requested cancel go back to index.php
if(isset($_POST['cancel'])){
header('Location: index.php');
return;
}
//handling incoming data
$uid = $_SESSION['user_id'];
if (isset($_POST['first_name']) && isset($_POST['last_name']) &&
isset($_POST['email']) && isset($_POST['headline']) && isset($_POST['summary'])){
if (strlen($_POST['first_name']) == 0 || strlen($_POST['last_name']) == 0 ||
strlen($_POST['email']) || strlen($_POST['headline']) == 0 || strlen($_POST['summary']) == 0){
$_SESSION['error'] = "All fields are required";
header("Location: add.php");
return;
}
if(strpos($_POST['email'], '#') === false){
$_SESSION['error'] = "Email address must contain #";
header("Location: add.php");
return;
}
$stmt = $pdo->prepare('INSERT INTO profile
(user_id, first_name, last_name, email, headline, summary)
VALUES ( :uid, :fn, :ln, :em, :he, :su)');
$stmt->execute(array(
':uid' => $uid,
':fn' => $_POST['first_name'],
':ln' => $_POST['last_name'],
':em' => $_POST['email'],
':he' => $_POST['headline'],
':su' => $_POST['summary'])
);
$_SESSION['success'] = "profile added";
header("location: index.php");
return;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Profile Add</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Adding Profile for UMSI</h1>
<form method="post" action="index.php">
<p>First Name:
<input type="text" name="first_name" size="60"/></p>
<p>Last Name:
<input type="text" name="last_name" size="60"/></p>
<p>Email:
<input type="text" name="email" size="30"/></p>
<p>Headline:<br/>
<input type="text" name="headline" size="80"/></p>
<p>Summary:<br/>
<textarea name="summary" rows="8" cols="80"></textarea>
<p>
<input type="submit" name="add" value="Add">
<input type="submit" name="cancel" value="Cancel">
</p>
</form>
</div>
</body>
</html>
here I created my connection to the database using pdo connection and also require my config.php file for database sign in credentials
here is my pdo.php code:
<?php
require_once 'config.php';
//setting DSN
$dsn = "mysql:host=$host;dbname=$dbname;charset=UTF8";
//creating a PDO instance
try{
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if($pdo){
echo "database connected Successfully";
return;
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
my database sign in credentials are in this file, the username, password and dbname are not necessarily correct, I only changed them for the sake of asking.
here is my config.php code:
<?php
//my variables
$host = 'localhost';
$user = 'myusername';
$password = 'mypass';
$dbname = 'mydb';
?>
my index.php code has a static display for the profile entries, I wanted to be able to add the profiles first so I can make it dynamically display the profiles but here is my index.php code:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>
enter code here
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Mandla'ke Makondo's Resume Registry</title>
<!-- bootstrap.php - this is HTML -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css"
integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r"
crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Mandla'ke Makondo's Resume Registry</h1>
<p>
<?php
if(isset($_SESSION['user_id'])){
echo " <a href='logout.php'>Logout</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<a href='login.php'>Please log in</a>";
}
?>
</p>
<?php
if(isset($_SESSION['user_id'])){
echo"<table border = '1'>
<tr><th>Name</th><th>Headline</th><th>Action</th><tr><tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td><td><a href = 'edit.php'>Edit</a> <a href = 'delete.php'>Delete</a></td></tr>
</table>";
echo "<a href='add.php'>Add New Entry</a>";
}
if(!isset($_SESSION['user_id'])){
echo "<table border='1'>
<tr><th>Name</th><th>Headline</th>
<tr>
<tr><td>
<a href='view.php?profile_id=5634'>srghrsh yteu yt uuu</a></td><td>
eyetu e5u5</td></tr>
</table>";
}
?>
</div>
</body>

Using php session to display two different html pages based on logged in status

I have created a login system with php, mysql, and html. I am trying to figure out how to display a different home page with html code based on whether someone is logged in or not.
I have tried to display profile button on the header if they are logged in and if they are not logged in it displays Login/Signup on the header.
index.php
<?php session_start();
include('server.php');
if (isset($_SESSION['username'])){
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Profile
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
<?php
}else{
// not logged in
}
?>
<!DOCTYPE html>
<html lang = "en">
<!--
Capstone Project "Zoeker"
Michael Burnett, Annie Lalor, Sophia Michael, Hannah Smith
5/6/2021
-->
<head>
<title>Home Page</title>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Stylesheets -->
<link rel="stylesheet" href="CSS/Normalize.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="CSS/Styles.css?v=<?php echo time(); ?>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<!-- Menu Bar -->
<div class="topnav" id="myTopnav">
<img src="Images/Logo.png" alt="Zoeker">
About
Contact
Stores Near You
Login/Signup
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<!-- Strip container for opening home page -->
<div class = "strip1">
</div>
<!-- FOOTER Containers-->
<div class="footer">
<div class="footer-box">
<ul>
<li><img src="Images/Logo.png" alt="Zoeker"></li>
</ul>
</div>
<div class="footer-box">
<h2>Navigation</h2>
<ul>
<li>Stores</li>
<li>About Us</li>
<li>Contact</li>
</ul>
</div>
<div class="footer-box">
<h2>Service Areas</h2>
<ul>
<li>Bloomington</li>
</ul>
</div>
<div class="footer-box">
<h2>Contact Us</h2>
<ul>
<li>812-123-4567</li>
<li>Support#Zoeker.com</li>
</ul>
</div>
</div>
</body>
</html>
server.php
<?php
session_start();
$username = "";
$email = "";
$errors = array();
//Connect to the database
$conn = mysqli_connect("db.luddy.indiana.edu", "i494f20_team36", "my+sql=i494f20_team36", "i494f20_team36");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: ";
}
//if the register button is clicked
if (isset($_POST['register'])){
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
//Check database for username and email already in use
$sql_u = "SELECT * FROM users WHERE username='$username'";
$sql_e = "SELECT * FROM users WHERE email='$email'";
$res_u = mysqli_query($conn, $sql_u);
$res_e = mysqli_query($conn, $sql_e);
//ensure form fields are filled in
if(empty($username)){
array_push($errors, "Username is required");
}
if(empty($email)){
array_push($errors, "Email is required");
}
if(empty($password)){
array_push($errors, "Password is required");
}
if(mysqli_num_rows($res_u) > 0) {
array_push($errors, "Username is already taken");
}
if(mysqli_num_rows($res_e) > 0) {
array_push($errors, "Email is already taken");
}
//if no errors, insert new user into database
if (count($errors) == 0){
$sql = "INSERT INTO users(username, email, password)
VALUES ('$username', '$email', '$password')";
mysqli_query($conn, $sql);
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}
else{
echo "not quite, but you'll get it";
}
}
// log user in from login page
if (isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username)){
array_push($errors, "Username is required");
}
if (empty($password)){
array_push($errors, "Password is required");
}
if (count($errors) == 0){
$sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1){
// log user in
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index.php'); //redirect to home page
}else{
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The else was empty and the html version for users that are not logged in was always shown. By moving the closing else-bracket to the end of the file, you get the 2 versions depending on the user being logged in or not.
<?php
}else{
// not logged in
// THE CLOSING BRACKET IS NOW AT THE BOTTOM
?>
<!DOCTYPE html>
<html lang = "en">
<!-- LINES DELETED FOR BREVITY ->
</body>
</html>
<?php } // MOVED CLOSING BRACKET TO THE END

processForm.php gives me a Zero value for Session Id

I want to store data (id, profile_image, caption) from another table
(I just download the code for uploading images)
The problem is when I am about to save the data, processForm.php always give me a zero value for Session ID which is my current ID is "1".
I'm a newbie here.
(login.php)
<?php
// Initialize the session
session_start();
// Check if the user is already logged in, if yes then redirect him to
welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
// Include config file
require_once "config.php";
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
// Check if password is empty
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
// Validate credentials
if(empty($username_err) && empty($password_err)){
// Prepare a select statement
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = $username;
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Store result
mysqli_stmt_store_result($stmt);
// Check if username exists, if yes then verify password
if(mysqli_stmt_num_rows($stmt) == 1){
// Bind result variables
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
// Password is correct, so start a new session
session_start();
// Store data in session variables
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
// Redirect user to welcome page
header("location: welcome.php");
} else{
// Display an error message if password is not valid
$password_err = "The password you entered was not valid.";
}
}
} else{
// Display an error message if username doesn't exist
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($link);
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<title>Fox - Log In | Sign Up</title>
<meta charset="windows-1252">
</head>
<body>
<div class="header" id="myHeader" >
<img src="logo.png" alt="Fox Logo" width="5%" height="20%">
<div class="tooltip">
<img src="text.png" alt="Fox text" width="50%" height="15%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="login.php">
</map>
</div>
<div class="container">
<img class="img" src="bg2.jpg">
</div>
<div class="signup"><br><br><br><br><br>
<h1 style="text-align:center; font-size:12;">Log In</h1><br>
<form style="margin-left:25px; margin-top: -20px;" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Username</p>
<input placeholder="Enter Username" type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<br><span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<p style="font-size: 14px; color: white;margin-left: 0px;width: 980px;">Password</p>
<input placeholder="Enter Password" type="password" name="password" class="form-control" >
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group">
<input style="margin-top:20px;" type="submit" class="button" value="Login">
</div>
<p2>Sign up now</p2>
</form>
</div>
<div>
<img class="user" src="user.png">
</div>
<a type="link2" style="margin:30px; text-decoration: none;" href="#">Terms & Policies</a>
<a type="link2" style="text-decoration: none;" href="#">Help</a>
</div>
</body>
</html>
(welcome.php)
<?php
require_once "config.php";
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body{ font: 14px sans-serif; text-align: center; }
</style>
</head>
<body>
<br>
<a style="margin-left:90%;position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<div style="margin-right:96%"class="tooltip">
<img style="margin-right: 96%;margin-top:0%;" src="logo.png" alt="Fox Logo" width="100%" usemap="#foxlogo">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
<hr>
<div class="profile">
<div class="page-header">
<h1><b><?php echo htmlspecialchars($_SESSION["username"]); ?></b></h1>
<div class="container">
<img name="profile" class="image" src="images/placeholder.png" id="profileDisplay" style="display: block;width: 45%;margin: 10px auto;border-radius:50%;"><br>
<input type="file" name="profileImage" id="profileImage" style="display: none;">
<div class="overlay">
<div class="text"><br>
Update Profile<br><br><br>
View profile
</div>
</div>
<?php
$con = mysqli_connect("localhost","root","","demo");
$q = mysqli_query($con,"SELECT * FROM users WHERE id ='{$_SESSION["id"]}'");
while($row = mysqli_fetch_assoc($q)){
echo $row['created_at'];
}
?>
</div>
<p>
Reset Your Password<br><br><br>
</p>
</div>
</body>
</html>
(config.php)
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
/* Attempt to connect to MySQL database */
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
(updateprofile.php)
I try to echo my current id(1) in this form and it is fine. but in saving id in XAMPP php my admin gives me ZERO. processForm gives me zero value for my SESSION ID
picture1:I try to echo my ID and its fine
Picture2:After I upload a picture. it gives me a zero value for ID
<?php
require_once "config.php";
include 'processForm.php';
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="home.css">
<link rel="icon" href="logo2.png" type="image">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<head>
<meta charset="UTF-8">
<title>Fox | Home</title>
<style type="text/css">
body, html{ font: 14px sans-serif; text-align: center;height: 100%; width: 100%; }
</style>
</head>
<body>
<div style="margin-left:90%"class="tooltip">
<span class="tooltiptext">Go To Fox Home</span>
</div>
<map name="foxlogo">
<area shape="rect" coords="0,0,133,126" href="welcome.php">
</map>
</div>
<img style="margin-right: 90%; margin-top:2%;" src="logo.png" alt="Fox Logo" width="5%" usemap="#foxlogo">
<a style="margin-left:90%; margin-top:-5%; position: relative;" href="logout.php" name="signout" class="btn btn-danger">Sign Out</a>
<hr>
<div style="margin-left: 35%"class="container">
<div class="row">
<div class="col-4 offset-m-d4 form-div">
<form enctype="multipart/form-data" action="index.php" method="post" >
<h3 class="text-center">Upload Profile</h3>
<?php //echo htmlspecialchars($_SESSION["username"]);
echo " My id is {$_SESSION["id"]}"; ?>
<div class="form-group text-center">
<img src="images/placeholder.png" id="profileDisplay" onclick="triggerClick()" style="display: block;width: 60%;margin: 10px auto;border-radius:50%;">
<input type="file" name="profileImage" onchange="displayImage(this)" id="profileImage" style="display: none;">
</div>
<div clas="form-group">
<label for="caption">Caption</label>
<textarea name="caption" id="caption" class="form-control"></textarea>
</div>
<div class="form-group">
<br>
<button type="submit" name="save-user" class="btn btn-primary btn-block">Upload</button>
</div>
</form>
</div>
</div>
</div>
<br><br><br><br>
<script src="scripts.js"></script>
</body>
</body>
</html>
(processForm.php)
<?php
require_once "config.php";
//connect db
$conn = mysqli_connect('localhost','root','','demo');
if(isset($_POST['save-user'])){
$caption = $_POST['caption'];
$profileImageName =time() . '_' . $_FILES['profileImage']['name'];
$target = 'images/' . $profileImageName;
if(move_uploaded_file($_FILES['profileImage']['tmp_name'], $target)){
//* */
$sql = "INSERT INTO photos (id,profile_image,caption) VALUES ('{$_SESSION['id']}','$profileImageName','$caption')";
if (mysqli_query($conn, $sql)){
$msg="Image uploaded and saved to database";
$css_class = "alert-success";
}else{
$msg="Database error: Failed to save user";
$css_class = "alert-danger";
}
//
$msg="Image uploaded";
$css_class = "alert-success";
header("location: welcome.php");
}else{
$msg="Failed to upload";
$css_class = "alert-danger";
header("location: updateprofile.php");
}
}
you can add the output of the $_SESSION variable with a var_dump(); After the loggin and another one in the same moment of the saved of the photo in mysql , and compare??? I think that your (processForm.php) is missing at the beginning too ... session_start ();

$_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?

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