Getting ID to edit record PHP + Oracle - php

I have php pages that let me view, add, delete records in database, but I can't make it work to edit record. I have problem to get id to edit_h.php. When i enter id number manually in ("UPDATE uzytkownik SET LOGIN = :login WHERE id = :id") it works fine. I am stuck with this problem for a bit now. Thanks for any help in advice.
Here's my code:
edit.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edytowanie uzytkownikow</title>
</head>
<body>
<form action="edit_h.php" method="post">
Login:<br>
<input type="text" name="login">
<br>
<input type="submit" value="Edytuj">
</form>
</body>
</html>
edit_h.php
<?php
include_once "polacz.php";
$id = $_GET['id'];
$login = $_POST['login'];
$con = polacz();
$stid = oci_parse($con, "UPDATE uzytkownik SET LOGIN = :login WHERE id = :id");
oci_bind_by_name($stid,':login',$login);
oci_bind_by_name($stid,':id',$id);
if (oci_execute($stid))
{
header("Location: view.php");
}
else
{
echo "blad";
}
view.php
<?php
include_once "polacz.php";
session_start();
if (!isset($_SESSION['id']))
{
header("Location: login.php");
die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Logowanie</title>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
text-align: left;
padding: 8px;
}
tr:nth-child(even){background-color: #f2f2f2}
th {
background-color: #af504c;
color: white;
}
</style>
</head>
<body>
<?php
echo "Witaj ".$_SESSION['login'];
echo '<br>WYLOGUJ SIĘ<br>';
$con = polacz();
if (isset($_GET['sort']))
{
$sort = (int)$_GET['sort'];
if ($sort == 1)
{
$sort = 2;
}
else
{
$sort = 1;
}
}
else
{
$sort = 1;
}
$dbsort =array(1=>'ASC',2=>'DESC');
$stid = oci_parse($con,"SELECT id, login FROM uzytkownik ORDER BY login ".$dbsort[$sort]);
oci_execute($stid);
echo "<table>";
echo "<tr><th>ID</th><th><a href=\"view.php?sort=$sort\">Login<th>Usun</th><th>Edytuj</th>
</th></tr>";
while (($row = oci_fetch_array($stid, OCI_ASSOC)) != false)
{
$id = $row['ID'];
$login = $row['LOGIN'];
echo "<tr><td>$id</a></td><td>$login</td>
<td>Usun
<td>Edytuj</tr>";
}
echo "</table>";
echo '<br>Dodaj uzytkownika<br>';
?>
</body>
</html>

Two possibilities here:
You have id stored in session already, so you could just get it from there:
// in edit_h.php - make sure you start session before!
$id = $_SESSION['id'];
Or you pass it along the various scripts:
// edit.php
<form action="edit_h.php" method="post">
Login:<br>
<input type="text" name="login">
<br>
<input type="submit" value="Edytuj">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
</form>
// edit_h.php
$id = $_POST['id']; // note, that this is stored in POST now!
Note, that it's not such a good idea to pass a plain id through scripts, as it could easily be hacked. So option 1 would be the better one (depending on how you get the id in first place)!

Related

Get value of html text field using sql query with php

LOGINPAGE.html:
This is where the user will input their username and password. PHP method is POST.
<html>
<head>
<title>
LOG IN
</title>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<form action = "loginDatabase.php" method = "POST">
<label>User name:</label>
<input type="text" id="userNameID" name="userNameName" required>
<br />
<label>Password:</label>
<input type="password" id="passwordID" name="passwordName" required>
<br />
<input type="submit" id="submitLoginID" name="submitLoginName">
</form>
</body>
</html>
LOGINDATABASE.php:
This is the processing part where the mysql query will reference the record to be displayed on ADMINPAGE.php based on the username given on LOGINPAGE.php. I cannot figure out want went wrong in line 7 since I always get an error Notice: Undefined index: userNameName in /opt/lampp/htdocs/UsersDatabaseProgram/loginDatabase.php on line 7
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include('connect.php');
session_start();
$result = mysqli_query($con, "SELECT * FROM addUsers WHERE userName = '" . $_GET['userNameName'] . "'");
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
$userName = $_POST['userNameName'];
$password = $_POST['passwordName'];
/*
This doesnt work
$email = $row['email'];
$userlevel = $row['userLevel'];
*/
$sql = "SELECT * FROM addUsers WHERE userName = '".$userName."' AND password = '".$password."'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
if ($row["userLevel"] == "user") {
$_SESSION["userName"] = $userName;
header('location: userPage.php');
} elseif ($row["userLevel"] == "admin") {
$_SESSION["userName"] = $userName;
header('location: adminPage.php');
} else {
echo "<h1> Login failed. Invalid username or password.</h1>";
}
}
?>
ADMINPAGE.php:
This is where the name of the user, user level, and user status will be displayed.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
include('connect.php');
include('loginDatabase.php');
?>
<html>
<head>
<style>
body {
text-align: center;
}
</style>
</head>
<body>
<h2>Admin</h2>
Log-out <br />
View records <br />
Add Record <br />
<label>Welcome</label><br />
<?php echo $_SESSION["userName"] ?>
<br />
<label>User level: </label>
<?php
while ($row = mysqli_fetch_array($result)) {
?>
<input type = "text" name = "userLevelName" value = " <?php echo $row['userLevel']; ?>"> <br />
<label>Email: </label>
<input type = "text" name = "userEmailName" value = " <?php echo $row['email']; ?>">
<?php
}
?>
<br />
</body>
</html>
You're sending the data as a POST then trying to access it as GET (then retrieving it again on line 11 !!).
Change it to something like this:-
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
$userName = $_POST['userNameName'];
$password = $_POST['passwordName'];
}
$result = mysqli_query($con, "SELECT * FROM addUsers WHERE userName = '$userName'");

PHP click count with mysqli

I want to make a program what will count clicks after click button.
I have this code but it don't work. I use mysqli to connect to database and I use query to insert value to database and query to select from database.
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])){
$connection=new mysqli("hidden","hidden","hidden","hidden");
if($connection == false){
die("Sorry jako");
}
$query="INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false){
die("Promiň");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
echo $row["klikcount"];
}
}
$klik=$klik+1;
}
?>
</form>
</body>
</html>
thanks.
I try solve your code and I made some changes.
Change position of "$klik = $klik+1;"
Add another SELECT
My new code:
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])) {
$connection = new mysqli("hidden","hidden","hidden","hidden");
if($connection == false) {
die("Sorry jako");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$klik = $row["klikcount"];
}
}
$klik = $klik+1;
$query = "INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false) {
die("Promiň");
}
$sql = "SELECT klikcount FROM klik";
$result = $connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["klikcount"];
}
}
}
?>
</form>
</body>
</html>

Converting username, to userID for entry into a comments box

<?php
include("connection.php");
session_start();
if($_SERVER["REQUEST_METHOD"] == "POST") {
// username and password sent from form
$myusername = mysqli_real_escape_string($conn,$_POST['username']);
$mypassword = mysqli_real_escape_string($conn,$_POST['password']);
$row['userID'] = $myuserid;
$sql = "SELECT * FROM u803621131_login.users WHERE username = '$myusername' and password = '$mypassword'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$active = $row['active'];
$count = mysqli_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count == 1) {
session_start("myuserid");
$_SESSION['login_user'] = $myusername;
$_SESSION['login_id'] = $myuserid;
header("location: welcome.php");
}else {
$error = "Your Login Name or Password is invalid";
}
}
?>
<html>
<head>
<title>Login Page</title>
<style type = "text/css">
body {
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
label {
font-weight:bold;
width:100px;
font-size:14px;
}
.box {
border:#666666 solid 1px;
}
</style>
</head>
<body bgcolor = "#FFFFFF">
<div align = "center">
<div style = "width:300px; border: solid 1px #333333; " align = "left">
<div style = "background-color:#333333; color:#FFFFFF; padding:3px;"><b>Login</b></div>
<div style = "margin:30px">
<form action = "" method = "post">
<label>UserName :</label><input type = "text" name = "username" class = "box"/><br /><br />
<label>Password :</label><input type = "password" name = "password" class = "box" /><br/><br />
<input type = "submit" value = " Submit "/><br />
</form>
<div style = "font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div>
</div>
</div>
</div>
</body>
</html>
Login.php - The login page with all the changed parts, the actual login works as it should. although it is hard to tell if there are any other issues
<?php session_start();
include'../../connection.php';?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<link rel="stylesheet" type="text/css" href=".../../../../style.css">
<title>Home</title>
<!--[if IE]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<?php include('../../main/main.php');?>
</head>
<body>
<div class=containermain>
<h1>I5-6600k.php</h1>
<form action="ratepost.php" method="post">
<label for="rating">rating:</label>
<select name="rating" id="rating" value="rating" >
<option>
<option value="1">1 </option>
<option value="2">2</option>
<option value="3">3 </option>
<option value="4">4</option>
<option value="5">5</option>
</option>
</select>
<input type="submit" value="Submit">
</form>
<h2>graphics card write up................</h2>
<?php echo "Hello " . $_SESSION['user']; ?>
<p> </p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
<!---------------------------------------COMMENT BOX---------------------------------------------------->
<div class="comments" align="center">
<form action="" method="post" >
<textarea rows="4" cols="50" name="comment">
Please type a comment if you are logged in....
</textarea>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_SESSION['login_id']) && !empty($_SESSION['login_id'])) {
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
if(mysqli_query($conn, $sqlinsert)){
header("Location: i5-6600k");
} else {
echo "ERROR: Could not able to execute $sqlinsert. " . mysqli_error($conn);
}
}
// close connection
$sql = "SELECT `users`.`username`, `comment`.`comment`, `comment`.`timestamp`\n"
. "FROM `users`\n"
. "LEFT JOIN `comment` ON `users`.`userID` = `comment`.`userID` \n"
. "where dCpuID = 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Username</th><th>Comment</th><th>Timestamp</th>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["username"]. "</td><td>" . $row["comment"]."</td><td>" . $row["timestamp"]. "</td>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
</div>
<?php include('../../assets/footer.php');?>
<div class="fb-comments" data-href="http://www.computercomparison.tk/#home" data-numposts="5"></div>
</body>
</html>
Have included entirety of 2nd page, incase there may be clashes with other parts of the code in the site that may be pointed out.
Also you will find lots of code in strange places, only testing bits at the mo.
<?php
include('connection.php');
session_start();
$user_check = $_SESSION['login_user'];
$ses_sql = mysqli_query($conn,"select username, from users where username = '$user_check' ");
$row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);
$login_session = $row['username'];
if(!isset($_SESSION['login_user'])){
header("location:login.php");
}
?>
Have this session.php file, didn't think it was too relevant but changing it around did affect logging in and stuff, it is in good condition here, wonder if there is anything i need to change here too? it is linked to the welcome.php
Following the error message you connected a column for the comment authors ID to one in your account table using a foreign key.
As shown in your picture they're both INT. But you are trying to insert a VARCHAR (the username) into this column instead.
My approach would be to get the user's ID by a sql query or even better save the users ID to the session:
session_start();
$_SESSION['login_user'] = $usernameFromFormOrWhatever;
$_SESSION['login_id'] = $usersID;
So you can fill your userID column with it:
$id = $_SESSION['login_id'];
$sqlinsert = "INSERT INTO comment (userID, comment, dCpuID) VALUES ('$id', '$comment', '1')";
Additionally the entered ID in your comments table must also appear in a row of your accounts table as ID of a user. Otherwise you will get an error message like you do now.

How to verify user details using PHP by retrieving data from SQLite3 database?

I am new to PHP coding. I have created two forms. One is for signing up and the other for logging in. Unfortunately both fail to work due to some issues in the queries. I also searched and went through similar posts on this site but none solved my problem. I want to verify whether a user with the same id exists in the database "Users.db" at the time of signing up if any user enters the same id he should be notified to enter a valid id.
When I run my "sign in.php" code, it displays the following message on the screen without even waiting for the user to press the submit button/ sign up button.. "Number of rows found: 1 .This id is not available. Please enter a valid id." This message gets displayed even if the user enters a unique id that doesnt exist in the database before. Nothing gets stored in my database even if the id is unique by pressing the sign up button.
Secondly while logging in, the id and password entered by the user must be verified and matched with those stored in the database. He should be directed to the "index.html" page after successfully login in and only if he has signed up before. He should also be able to view his search history that is stored in "Search" table in the same database. This table contains two columns. One for the User id and the other for saving his search results.
The Search table looks like:
Id | History
nl23 Grand Hayat Hotel
Pearls Residencia Hotels
I am getting this error after running my code for login form "Unable to prepare statement: 1, near "AND": syntax error in D:\log in.php on line 54".
My log in form code is below:
log in.php
<body>
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['uid'])) {
$id = $_POST['uid'];
}
if (isset($_POST['passid'])) {
$pass = $_POST['passid'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
?>
</body>
</html>
My sign in form is below:
sign in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
// $ret = $db->query($result);
//$ret = $db->exec($sql);
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
?>
</body>
</html>
Please guide me as i am stuck in both these codes.
What you are missing is checking if $_POST is set or is not empty. Only then you want to process user input. One more thing is that you should wrap $pass in quotes as it is a string and will be interpreted as column name if not surrounded with quotes.
Here's code:
log in.php
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Log in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
<input type="submit" name="submit" value="Log In" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$pass=null;
$id_exists=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$pass = $_POST['Password'];
}
$sql= " SELECT * FROM Users WHERE ID = '" .$id. "' AND PASSWORD = '" .$pass. "';";
$ret = $db->query($sql);
$rows = count($sql);
if ($rows > 0)
{
$id_exists = true;
echo "You entered a valid id and password. ";
$sql= "SELECT History FROM Search WHERE Id= " .$id. ";";
$ret = $db->query($sql);
//header("location:index.html");
}
else
{
echo "Please enter a valid id and password. ";
}
}
?>
</body>
</html>
sign in.php:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
label{display:inline-block;width:100px;margin-bottom:10px;}
</style>
</head>
<body>
<h2>Sign in page</h2>
<form method="post" action="">
Id: <input type="text" name="Id">
<br><br>
Password: <input type="text" name="Password">
<br><br>
Email: <input type="text" name="Email">
<input type="submit" name="submit" value="Sign Up" >
</form>
<?php
if(!empty($_POST)) {
class MyDB extends SQLite3
{
function __construct()
{
$this->open('Users Data.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
}
$id=null;
$password=null;
$email=null;
$id_exists=false;
$sql=null;
$result=null;
$rows=null;
$ret=null;
if (isset($_POST['Id'])) {
$id = $_POST['Id'];
}
if (isset($_POST['Password'])) {
$password = $_POST['Password'];
}
if (isset($_POST['Email'])) {
$email = $_POST['Email'];
}
$result= "SELECT * FROM Users WHERE ID = " .$id. ";";
echo "<p> The result query is ".$result ."</p>";
$rows = count($result);
echo "<p> Number of rows found: ".$rows ."</p>";
if ($rows > 0)
{
$id_exists = true;
echo "This id is not available. Please enter a valid id. ";
}
else
{
$sql= "INSERT INTO Users (ID,PASSWORD, EMAIL)
VALUES ('$id','$password','$email');" ;
$ret = $db->query($sql);
//$ret = $db->exec($sql);
// header("location:index.html");
}
if(!$ret){
echo $db->lastErrorMsg();
} else {
}
$db->close();
}
?>
</body>
</html>

Simple PHP Session variables

I can't figure out why the following PHP won't work properly:
<?php
//Authenticate user credentials
function authenticate($name, $password) {
$sql = "SELECT *
FROM users
WHERE username = '$name'
AND password = '" . md5($password) . "'";
$result = mysql_query($sql);
if ($row = mysql_fetch_array($result)) {
//Successful login
echo "Welcome back, " . $row['username'] . "!";
return true;
} else {
//Failed login
echo "Invalid username or password";
return false;
}
}
function addUser($name, $password) {
$sql = "INSERT
INTO users (username, role, password)
VALUES ('$name', 'CHAIR', '". md5($password) . "');";
mysql_query($sql);
}
function createTables() {
$sql = "CREATE TABLE Users (
Create table Users(
username varchar(50) NOT NULL,
role ENUM('CHAIR', 'FACULTY', 'STAFF') NOT NULL,
password varchar(255) NOT NULL,
email varchar(50) NOT NULL PRIMARY KEY,
applicant_client_id varchar(50) NOT NULL,
countries varchar(50),
research_area varchar(255),
numAssignedReviews TINYINT UNSIGNED,
available varchar(50),
workload FLOAT UNSIGNED
);"
;
mysql_query($sql);
}
session_start();
if (isset($_SESSION['loggedIn'])) {
echo '<script> alert("LoggedIn is set") </script>';
$con = mysql_connect("localhost", "ttony21_Tony", "cse308");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ttony21_GARS", $con);
$name = $_POST["name"];
$password = $_POST["password"];
if (authenticate($name, $password)) {
$_SESSION['loggedIn'] = true;
}
mysql_close($con);
} else {
$_SESSION['loggedIn'] = false;
echo '<script> alert("LoggedIn is not set") </script>';
}
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>GARS</title>
<style type="text/css">
body {
text-align: center;
min-width: 600px;
}
#wrapper {
margin: 0 auto;
width: 600px;
text-align: left;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
</head>
<body>
<div class = "wrapper">
<?php
if ($_SESSION['loggedIn']) {
echo '
<div class = "upload">
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</div>
';
} else {
echo '
<div class = "login">
<form action = "/" id = "loginForm" method = "post">
<p>
Username: <input type = "text" name = "name" />
<br />
Password: <input type = "password" name = "password" />
<br />
<input type = "submit" id= "submit"/>
</p>
</form>
</div>
';
}
?>
</div>
</body>
</html>
There's a form: <form action = "/" id = "loginForm" method = "post">
When I either submit the form, or refresh the page, it should alert me with the message "LoggedIn is set" correct? But I only get the message "LoggedIn is not set."
I know that the session starts and the loggedIn is set properly, but I seem to lose the variable when I refresh the page or use the form, which shouldn't happen because it's a session variable right?
I'm new to using them so any help would be appreciated.
Session_Start() should be before the if statement, not in the else part.
<?php
session_start();
if (isset($_SESSION['loggedIn'])) {
echo '<script> alert("LoggedIn is set") </script>';
...
} else {
$_SESSION['loggedIn'] = false;
echo '<script> alert("LoggedIn is not set") </script>';
}
?>
I would slightly modify that to clarify that session_start() should be at the very beginning of the page, before any HTML is output. Once HTML has been output, a session won't start.
If you want to read the $_SESSION global, you must have started a session. i.e session_start(); must have been called. When logging in you might need to start it two times: once for the validation of the user and doing something like $_SESSION['status'] = 'authorized'; Then generally you create a redirect with header('Location : somewhere'); I am no professional on the header() function, but I know that after it you must do session_start() again if you want to read from the $_SESSION global variable.
From http://php.net/manual/en/function.session-start.php
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
So you need call session_start every request.

Categories