There may be better ways of doing this, but I'm pretty sure I should still get my session_id() passed to the second page. Instead, calling this on page 2 as my first few lines generates a brand new session_id() than the one created on page 1.
PAGE 2 BEGINNING:
<?php
error_reporting(E_ALL);ini_set('display_errors',1);
session_start();
echo session_id();
$sessionid = session_id();
echo "sessionNUM          = $sessionid\n";
echo "<br>";
echo '<pre>' .print_r($_SESSION, TRUE) . '</pre>';
PAGE 1 ALL:
<?php
error_reporting(E_ALL);ini_set('display_errors',1);
session_start();
$sessionid = session_id();
$currentDate = date('Y-m-d');
//echo "sessionNUM          = $sessionid\n";
//echo "<br>";
//echo "<br>";
//echo '<pre>' .print_r($_SESSION, TRUE) . '</pre>';
session_unset();
$old_sessid = session_id();
session_regenerate_id();
$new_sessid = session_id();
session_id($old_sessid);
session_destroy();
session_regenerate_id(FALSE);
session_start();
echo session_id();
echo "<br>";
$sessionid = session_id();
$currentDate = date('Y-m-d');
echo "sessionNUM          = $sessionid\n";
echo "<br>";
echo "<br>";
echo '<pre>' .print_r($_SESSION, TRUE) . '</pre>';
//Connect to DB
require_once 'configPOS.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
//Enter Session ID and set Order ID
//search for session info already exsiting
$result=$conn->query("SELECT * FROM POS_HEADERS WHERE sessionid='$sessionid' AND date='$currentDate'");
echo mysql_error();
if(mysqli_num_rows($result) > 0){
echo "session info already exists";
}
else{
echo "test.";
/*
$sessionid = session_id();
*/
$sql="INSERT INTO POS_HEADERS (sessionid, date)
VALUES('$sessionid', '$currentDate')";
if ($conn->query($sql) === TRUE) {
echo "New order started.<br>";
}
else {
echo "Error " . $sql . "<br>" . $conn->error;
}
}
$res=$conn->query("select ORDID from POS_HEADERS where sessionid='$sessionid'");
list($ORDERNUM)= $res->fetch_row();
//echo "<br>";
echo "<br>";
echo "ORDERNUM          = $ORDERNUM\n";
$_SESSION["OrderNum"] = $ORDERNUM;
echo "<br>";
//echo "<br>";
echo "Session variables are set.";
$res=$conn->query("select ORDID from POS_HEADERS where sessionid='$sessionid'");
list($ORDERNUM)= $res->fetch_row();
echo "ORDERNUM= $ORDERNUM\n";
//echo "<br>";
echo $_SESSION["OrderNum"];
$ordernum= $ORDERNUM;
echo $ordernum;
echo '<br>';
$LOCATION = $_POST["pickedlocation"];
echo $LOCATION;
echo "<br>";
echo "<br>";
echo "END Debugging Info";
echo "<br>";
echo "<br>";
echo '<pre>' .print_r($_SESSION, TRUE) . '</pre>';
echo "<br>";
echo session_id();
echo "<br>";
?>
<input type="button" value="Home" class="homebutton" id="btnHome"
onClick="window.location = 'https://www.example.com/POS/home.php'" />
My original problem was
PAGE 2 having one session_id(), lets call it "A",
PAGE 3 had a previous session(id), lets call it "B",
PAGE 4 had session_id() "A" again, and
PAGE 5 had session_id() "B" again.
All pages 2-5 do are insert data into a database for that session_id(), but for some reason PAGE 2 kept creating a new session_id() after PAGE 1 created one, which has got me to where I am now.
Things I have discovered - The session_save_path() is writeable, the url path is identical up to the page (...). Also, on the same URL there are very similar pages in a different directory that work flawlessly, so I think it's a code error, not a php.ini error.
First, Is your browser rejecting a cookie? In that case, you may always get a new session id. Different browsers have different options/panel to accept a cookie.
Second, edit the following fields in php.ini to suitable values.
session.use_cookies
session.save_path
session.use_trans_sid
Two pages have different session_start() calls? If you want to use one session_id for all your pages you should use only one for session_start() call for both of that files.
For example, create the third page let's name it bootstrap.php and include it at the beginning of the PAGE1 and PAGE2. In this file, you can start your session.
Hope I understand your problem correctly.
Related
I am building a pagination (SERP). Stuck on a single issue. The $_SESSION['row_count'] auto changes on every page load. Same page load. I can't figure-out why this unpermitted activity takes place by php.
This is a one page membership script (one page site) I am building. That means, register, login, logout, account homepage, search & pagination are not all different pages but one page where each have their own parts (functions).
The log & reg parts of the codes (functions) work. Only the keyword search & pagaination part of the script is failing due to the $_SESSION['row_count'] = 5 auto switching to $_SESSION['row_count'] = 0 on every page load.
Because my keyword search has 5 matches and due to me setting it to show 1 row per page, I should see 5 pages with a total of 5 rows or 1 row per page.
The PAGE 1 manages to show 1 matching row as expected. It's just, when I click any page (PAGE 2/PAGE3/PAGE4/PAGE5) then the $_SESSION['row_count'] = 5 auto switches to $_SESSION['row_count'] = 0 and so the sql_query fetches no rows.
//Grab total number of pages to paginate.
$row_count = $_SESSION['row_count'];//Pages beyong PAGE 1 this switches value from 5 to 0. That is BIG ISSUE! Why the switching ?
$total_pages = ceil($row_count/$result_per_page);
After clicking the SEARCH button, this part of my code yields $SESSION['row_count'] = 5. So far so good.
$query_1 = "SELECT COUNT(id) FROM users WHERE first_name = ? AND marital_status = ?";
$stmt_1 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_1,$query_1))
{
mysqli_stmt_bind_param($stmt_1,"ss",$_POST["first_name"],$_POST["marital_status"]);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
$_SESSION['row_count'] = $row_count;
NOTE:
I am successfully shown the matching rows on PAGE 1. Since I set it to display 1 row per page, I am shown 1 matching row. So far, so good.
Now, when I click PAGE 2 on the PAGINATION section, I expect to see the 2nd matching row, but "$SESSION['row_count'] = 5" auto switches to "$SESSION['row_count'] = 0" and so no matching rows get shown. I repeat: Why the switching of values from '5' to '0' when I click PAGE 2 or onwards ?
This illegal switching ruins this following query that runs when I click PAGE 2 or any PAGE beyond PAGE 1:
$row_count = $_SESSION['row_count'];
//$total_pages = ceil($result_1/$result_per_page); //Should I keep this line or the line below ? Which one ?
$total_pages = ceil($row_count/$result_per_page); //Should I keep this line or the line above it ? Which one ?
CONTEXT:
<?php
error_reporting(E_ALL);
session_start();
?>
<!DOCTYPE HTML">
<html>
<head>
<meta name="viewport" content="width-device=width, initial-scale=1">
</head>
<body>
<?php
if(!isset($_GET['query_type']) && empty($_GET['query_type']))
{
die("Invalid Query!");
}
else
{
$_SESSION['query_type'] = $_GET['query_type']; echo __LINE__; echo "<br>";//DELETE
}
echo __LINE__; echo "<br>";//DELETE
if(!isset($_GET['form_type']) && empty($_GET['form_type']))
{
die("Invalid Form!");
}
else
{
$_SESSION['form_type'] = $_GET['form_type']; echo __LINE__; echo "<br>";//DELETE
if(!function_exists($_SESSION['form_type']))
{
die("Invalid Form!");
}
else
{echo __LINE__; echo "<br>";//DELETE
if(!isset($_SESSION['form_step']))// || $_SESSION['form_step'] != 'end')
{
$_SESSION['form_step'] = 'start'; echo $_SESSION['form_step'];
echo __LINE__; echo "<br>";//DELETE
$_SESSION['form_type']();
}
else
{
$_SESSION['form_step'] = $_GET['form_step'];
echo __LINE__; echo "<br>"; echo $_SESSION['form_step'];//DELETE
$_SESSION['form_type']();
}
}
}
//FUNCTIONS START FROM HERE
function search()
{echo __LINE__; echo "<br>";//DELETE
function rows_count()
{
//Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME).
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("localhost","root","","powerpage");
$conn->set_charset('utf8mb4'); //Always set Charset.
if($conn === false)
{
die("ERROR: Connection Error!. " . mysqli_connect_error());
}
$query_1 = "SELECT COUNT(id) FROM users WHERE first_name = ? AND marital_status = ?";
$stmt_1 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_1,$query_1))
{
mysqli_stmt_bind_param($stmt_1,"ss",$_POST["first_name"],$_POST["marital_status"]);
mysqli_stmt_execute($stmt_1);
$result_1 = mysqli_stmt_bind_result($stmt_1,$row_count);
mysqli_stmt_fetch($stmt_1);
$_SESSION['row_count'] = $row_count;
echo __LINE__; echo "<br>";//DELETE
$_SESSION['form_step'] = 'end'; //$form_step = 'end'; WRONG
//fetch_rows();
}
//Close Statement.
mysqli_stmt_close($stmt_1);
//Close Connection.
mysqli_close($conn);
}
function fetch_rows()
{ echo __LINE__; echo "<br>";//DELETE
$form_step = $_GET['form_step'];
$page_number = $_GET['page'];
$result_per_page = $_GET['page_limit'];
$offset = (($page_number * $result_per_page) - $result_per_page); //Offset (Row Number that 'Starts' on page).
$last_row_on_page = ($page_number * $result_per_page); //Max Result (Row Number that 'Ends' on page).
$previous_page = $page_number-1;
$next_page = $page_number+1;
echo "Row Start: $offset";echo "<br>";
echo "Row End: $last_row_on_page";echo "<br>";
//Connect to Database. (DB_SERVER, BD_USERNAME, DB_PASSWORD, DB_NAME).
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = mysqli_connect("localhost","root","","powerpage");
$conn->set_charset('utf8mb4'); //Always set Charset.
if($conn === false)
{
die("ERROR: Connection Error!. " . mysqli_connect_error());
}
$query_2 = "SELECT * FROM users WHERE first_name = ? AND marital_status = ? ORDER BY id LIMIT $offset,$last_row_on_page";
$stmt_2 = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt_2,$query_2))
{echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 111.
mysqli_stmt_bind_param($stmt_2,"ss",$_POST["first_name"],$_POST["marital_status"]);
mysqli_stmt_execute($stmt_2);
$result_2 = mysqli_stmt_get_result($stmt_2);
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 114.
//Grab total number of pages to paginate.
$row_count = $_SESSION['row_count'];
//$total_pages = ceil($result_1/$result_per_page);
$total_pages = ceil($row_count/$result_per_page);
echo "TOTAL PAGES: $total_pages<br><br>";
while($row = mysqli_fetch_array($result_2,MYSQLI_ASSOC))
{echo __LINE__; echo "<br>";
//Retrieve Values.
$id = $row["id"];
$first_name = $row["first_name"];
$middle_name = $row["middle_name"];
$surname = $row["surname"];
$gender = $row["gender"];
$marital_status = $row["marital_status"];
$working_status = $row["working_status"];
echo "Id: $id<br>";
echo "First Name: $first_name<br>";
echo "Middle Name: $middle_name<br>";
echo "Surname: $surname<br>";
echo "Gender: $gender<br>";
echo "Marital Status: $marital_status<br>";
echo "Working Status: $working_status<br>";
echo "<br>";
echo "<br>";
}
$i = 1;
while($i<=$total_pages)
{
if($i<$total_pages)
{
echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW_1.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=2&page=<?php echo $i;?>'><?php echo " $i ";?></a><?php
}
elseif($i==$page_number)
{
echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW_1.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=2&page=<?php echo $i;?>'><?php echo "<b> $i </b>";?></a><?php
}
$i++;
}
if($page_number>$total_pages)
{
echo "<a href='http://localhost/power.page/pagination_test_simple_WORKING_ON_NOW_1.php?form_type=";?><?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=2&page=<?php echo $previous_page;?>'><?php echo "<b> Previous </b>";?></a><?php
}
}
//Close Statement.
mysqli_stmt_close($stmt_2);
//Close Connection.
mysqli_close($conn);
$_SESSION['form_step'] = 'end';
//die();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>?form_type=<?php echo $_SESSION['form_type'];?>&query_type=<?php echo $_SESSION['query_type'];?>&form_step=end&page_limit=2&page=1" method='post' enctype='plain/text'>
<?php
//Added '*' (asterisk) to indicate the 'Text Field' is a 'required' one.
echo "<label for=\"first_name\">First Name *:</label>
<input type=\"text\" name=\"first_name\" placeholder=\"First Name\" value = \"\">";?>
<br>
<?php
echo "<label for=\"marital_status\">Marital Status *:</label>";
echo "<select name=\"marital_status\">";
echo "<option value=\"single\">Single</option>";
echo "<option value=\"married\">Married</option>";
echo "</select>";
echo "<br>";
?>
<input type="submit" name="search" value="Search">
<?php
//$current_function = __FUNCTION__;
//echo $current_function;
//Do following if "Search" button clicked.
if($_SERVER['REQUEST_METHOD'] === 'POST')
{echo __LINE__; echo "<br>";//DELETE
//Do following if "Search" button clicked.
if(isset($_POST['search']))
{echo __LINE__; echo "<br>";//DELETE
rows_count(); //This function will forward script flow to fetch_rows() before halting the script.
fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? IT IS LINE: 200. MAIN ISSUE HERE, I SUSPECT.
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 201.
die;
}
}
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS FAILS TO ECHO. IT IS LINE: 198.
//Do following if "Search" button not clicked but pagination numbered links are clicked. Eg Page 1, 2, 3, etc..
//rows_count(); //This function will forward script flow to fetch_rows() before halting the script.
fetch_rows(); //On PAGINATION PAGE 2, THIS FUNCTION IS NOT GETTING TRIGGERED! WHY ? IT IS LINE: 200. MAIN ISSUE HERE, I SUSPECT.
echo __LINE__; echo "<br>";//On PAGINATION PAGE 2, THIS GETS ECHOED. IT IS LINE: 201.
die;
}
?>
NOTE: I moved the session_start() to the top of the file underneath the error_reporting() but no luck. I even switched form method='post' to 'get' and tested. No luck. So, switched it back.
Php Folks,
Why on the second-page load (same page), the ELSEIF does not trigger?
My Expectation:
On the 1st page load, the IF should trigger since there are no sessions at the beginning.
Then a session should start. Set to '$_SESSION['form_step'] = 'start'.
Finally, set to:
$_SESSION['form_step'] = 'end';
On the 2nd page load (same page reloaded), the ELSEIF should trigger since a session was started previously and set to: $_SESSION['form_step'] = 'end'.
if(!session_id() || $_SESSION['form_step'] != 'end')
{
session_start();
$_SESSION['form_step'] = 'start';
echo "Line: 28 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 29 "; echo "New Session Id: "; echo session_id(); echo "<br>";
$_SESSION['form_step'] = 'end';
}
elseif($_SESSION['form_step'] == 'end')
{
echo "Line: 35 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 36 "; echo "New Session Id: "; echo session_id(); echo "<br>";
}
Result:
On the second page-load or same page reload, even though a session exists, the ELSEIF doesn't trigger but the IF triggers instead as if there were no sessions in existence or no sessions were started previously or no sessions been started yet.
Why is that? When you test the code you will see:
On the 1st page load, the IF will trigger.
So far, so good.
But refreshing the page would result in the same IF getting triggered again instead of the ELSEIF!
Not good!
Puzzling. I am confused.
On every page reload, I get echoed the same:
Line: 28 Session Step: start
Line: 29 New Session Id: ri4pbr42623g9uoaiiq3ebr41r
EDIT 1
I edited code to following based on Alvaro Gonzales and Ben Foster advice:
<?php
error_reporting(E_ALL);
session_start();
if(!session_id() || session_id() != $session_id || $_SESSION['form_step'] != 'end')
{
session_start();
$_SESSION['form_step'] = 'start';
echo "Line: 28 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 29 "; echo "New Session Id: "; echo session_id(); echo "<br>";
$_SESSION['form_step'] = 'end';
$session_id = session_id();
}
elseif($_SESSION['form_step'] == 'end') //Q2. WHY THIS IF GETS TRIGGERED WHEN CLICKING ANY NUMBERED PAGE LINKS (ON PAGINATION SECTION (EG PAGE 1 2 3 ETC.)) SINCE SESSION ID ALREADY EXISTS DUE TO ['form_step'] = 'end' ?
{
echo "Line: 35 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 36 "; echo "New Session Id: "; echo session_id(); echo "<br>";
}
I now get this error:
Notice: Undefined variable: session_id in
C:\xampp\htdocs\power.page\pagination_test_SIMPLE.php on line 5
Notice: session_start(): A session had already been started - ignoring
in C:\xampp\htdocs\power.page\pagination_test_SIMPLE.php on line 7**
Along with the error, I get my echoes:
Line: 28 Session Step: start
Line: 29 New Session Id: s3sojmnogkhkmga43fhk1u2j17**
How to fix this without seeing errors?
NOTE: At the very 1st time the page loads, I need to the IF to get triggered so it finds no sessions and creates one.
Sets $_SESSION['form_step'] = 'start';
Then $_SESSION['form_step'] = 'end';
Then when I reload the page, I need PHP to find the $_SESSION['form_step'] == 'end' and trigger the IFELSE and not the same IF again.
Why I need the ELSEIF triggered on the page reload? is because when the page is reloaded I need task 2 to trigger. While when the page is loaded for the 1st time I need task 1 to trigger.
IF deals with task 1. ElseIF deals with task 2.
This is a complex script. I only gave a relevant snippet here.
EDIT 2
If I leave the IF to this:
if(!session_id())
Then the IF never triggers. Always the ELSE.
I need the IF to trigger on the very 1st time the page loads and initiate the session and do the 1st task.
Then as long as the session exists, on every page refresh/reload, I need the ELSEIF to trigger to do the 2nd task.
This code doesn't work ...
<?php
error_reporting(E_ALL);
session_start();
if(!session_id())
{
session_start();
$_SESSION['form_step'] = 'start';
echo "Line: 28 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 29 "; echo "New Session Id: "; echo session_id(); echo "<br>";
$_SESSION['form_step'] = 'end';
$session_id = session_id();
}
elseif($_SESSION['form_step'] == 'end')
{
echo "Line: 35 "; echo "Session Step: "; echo $_SESSION['form_step']; echo "<br>";
echo "Line: 36 "; echo "New Session Id: "; echo session_id(); echo "<br>";
}
session_start() needs to be called before attempting to access any session variable, even when refreshing the page.
So when refreshing the page, a session is not currently active. Hence your if statement evaluates to true.
Try moving session_start() to the top of your file.
What you are trying to do is very unclear to me. But this should work (based on my understanding of the expected behavior).
error_reporting(E_ALL);
session_start();
if (!isset($_SESSION['form_step']) || $_SESSION['form_step'] !== 'end') {
// This will be overwrited before the end of this page load.
$_SESSION['form_step'] = 'start';
echo "Line: ".__LINE__;
echo "Session Step: ";
echo $_SESSION['form_step'];
echo "<br>";
echo "Line: ".__LINE__;
echo "New Session Id: ";
echo session_id();
echo "<br>";
$_SESSION['form_step'] = 'end';
// This variable is never used, you might want to get rid of it.
$session_id = session_id();
} else {
echo "Line: ".__LINE__;
echo "Session Step: ";
echo $_SESSION['form_step'];
echo "<br>";
echo "Line: ".__LINE__;
echo "New Session Id: ";
echo session_id();
echo "<br>";
}
I am trying to display information regarding the user after they have logged in. After the user has logged in the user will be redirected to success.php. I use MySQL and a form is an HTML form.
I tried writing the success page in two different ways
success.php (1)
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
include ("getUser.php");
// header("Location: getUser.php");
echo "done";
}
success.php (2)
<?php
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
echo "done";
}
?>
<h2>you have logged in</h2>
<p><?php include ("getUser.php");?></p>
I tried to include a file getUser.php that is suppose to retrive everything regarding the user.
getUser.php
$username = mysqli_real_escape_string($connection, $_REQUEST['username']);
$sql= "select * from userTable where username = '$username'";
if($result = mysqli_query($connection, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<table";
echo "<tr>";
echo "<th>username</th>";
echo "<th>city</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No user" . mysqli_error($connection);
}
}
I keep getting the "No user" error message from the getUser.php. I do not understand why I get it
In getuser.php you didnt make connection with your database.So add the below line at top of your php document.
$connection = new mysqli("HOST_NAME","USER_NAME","PASSWORD","DATABASE_NAME") or die("Connect failed: %s\n". $connection -> error);
This more than likely will not solve your issue but I believe it could lead you closer or help us better understand what is going on. I can't comment yet so I am posting it here and will continue to help you along until we solve the problem.
Add this to the top of your php documents:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
It will write errors to a text document stored on your server to help us debug your issue.
The following code works on my desktop in chrome for setting up a session. However, on my phone in chrome it constantly gives new sessionid upon refreshing. I've read through the other posts on her about a new sessionid every time and it seems to come down to permissions but there are no answers given. Is there something I can do to ensure this works on everyone's device, or is there a better way? I was trying to make a simple online ordering site for my restaurant.
<html>
<head>
<title>Online Ordering</title>
</head>
<style>
h3 {
text-align: center;
}
h5 {
text-align: center;
}
</style>
<body>
<?php
session_start();
$sessionid = session_id();
$currentDate = date('Y-m-d');
echo "sessionNUM          = $sessionid\n";
echo "<br>";
//Connect to DB
require_once 'configordonline.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
//Enter Session ID and set Order ID
//search for session info already exsiting
$result=$conn->query("SELECT * FROM HEADERS WHERE sessionid='$sessionid' AND date='$currentDate'");
echo mysql_error();
if(mysqli_num_rows($result) > 0){
echo "session info already exists";
}
else{
session_start();
$sessionid = session_id();
$sql="INSERT INTO HEADERS VALUES (NULL, '$sessionid', '$currentDate', 'noneyet')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error " . $sql . "<br>" . $conn->error;
}
}
$res=$conn->query("select ORDID from HEADERS where sessionid='$sessionid'");
list($ORDERNUM)= $res->fetch_row();
echo "<br>";
echo "<br>";
echo "ORDERNUM          = $ORDERNUM\n";
$_SESSION["OrderNum"] = $ORDERNUM;
echo "<br>";
echo "<br>";
echo "Session variables are set.";
?>
</body>
</html>
output on desktop:
sessionNUM = 055666a122f5f77e748880c5e488c443
session info already exists
ORDERNUM = 77
Session variables are set.
on mobile (new sessionNUM and ORDERNUM on every refresh:
sessionNUM = a703f4b3492be025c7b01cda45fb3653
New record created successfully
ORDERNUM = 113
Session variables are set.
Per this post, I discovered that the session start should come before the html, then the rest of the php after.
Login works on desktop but not mobile?
It seems to be working fine now.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
session_start();
?>
<html>
<head>
<title>Online Ordering</title>
</head>
<style>
h3 {
text-align: center;
}
h5 {
text-align: center;
}
</style>
<body>
<?php
$sessionid = session_id();
$currentDate = date('Y-m-d');
echo "sessionNUM          = $sessionid\n";
echo "<br>";
//Connect to DB
require_once 'configordonline.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
//Enter Session ID and set Order ID
//search for session info already exsiting
$result=$conn->query("SELECT * FROM HEADERS WHERE sessionid='$sessionid' AND date='$currentDate'");
echo mysql_error();
if(mysqli_num_rows($result) > 0){
echo "session info already exists";
}
else{
$sessionid = session_id();
$sql="INSERT INTO HEADERS VALUES (NULL, '$sessionid', '$currentDate', 'noneyet')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error " . $sql . "<br>" . $conn->error;
}
}
$res=$conn->query("select ORDID from HEADERS where sessionid='$sessionid'");
list($ORDERNUM)= $res->fetch_row();
echo "<br>";
echo "<br>";
echo "ORDERNUM          = $ORDERNUM\n";
$_SESSION["OrderNum"] = $ORDERNUM;
echo "<br>";
echo "<br>";
echo "Session variables are set.";
?>
management.php is the code which get information in php by a table.
And managementdel.php is the code which del the information.
I use mysql_fetch_array to show all data,and beside every information have a herf to delete
echo data in database.
When I del ,there no error inside.but database information haven't delete.
management.php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid=$row[0]'>get information</a></td><td>$row[0]</td><td><input type=text id='row1' name='row1' value='$row[1]' /></td>
<td>$row[2]</td><td>
<a href='searchtable.php?lid=$row[0]'>Change</a></td><td>
<a href='managementdel.php?lid=$row[0]'>Delete</a></td></tr>";
}
echo "</table>";
managementdel.php
<?php
$ac = $_GET['rowname'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>
There is so much stuff wrong with your script, I won't address it all. What I will do is answer your question that you asked which is: "Why it won't delete from database."
What is wrong in your script:
Using depreciated mysql_* library (See notes below)
Using meta refresh to redirect instead of something like header('Location: link');
Not sanitizing user input -> $_GET['lid'].
Posting user password in the table. (Hopefully not being stored as plaintext)
As stated, you're trying to get:
$_GET['rowname']
When you are sending lid -> managementdel.php?lid=$row[0]. You have to change that to:
$ac = $_GET['lid'];
NOTES
Please stay away from mysql_* functions as the library is depreciated.
Use either of the following two instead:
PDO
Mysqli Prepared Statements
And if you aren't going to do that, atleast try and sanitize your user inputs to prevent SQL Injections.
Using functions like intval() and mysql_real_escape_string() will help you but won't be as comprehensive as PDO/mysqli.
in managementdel.php file instead of
$ac = $_GET['rowname'];
there should be
$ac = $_GET['lid'];
Try
management.php
<?php
$con1 = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql1 = "Select LoginID , Password , Permission
from loginacc where Permission = 2 ";
$results = mysql_query($sql1,$con1);
echo "<tr><th>會員帳號</th></tr>";
echo "<table border=5 cellpadding=10>";
echo "<tr><th></th><th>帳號</th><th>密碼</th><th>權限</th><th></th><th></th></tr>";
while($row = mysql_fetch_array($results)) {
echo "<tr><td>
<a href='searchtable.php?lid= " . $row[0] . "'>get information</a></td><td>" . $row[0] . "</td><td><input type=text id='row1' name='row1' value='" . $row[1] . "' /></td>
<td>" . $row[2] . "</td><td>
<a href='searchtable.php?lid=" . $row[0] . "'>Change</a></td><td>
<a href='managementdel.php?lid=" . $row[0] . "'>Delete</a></td></tr>";
}
echo "</table>";
?>
managementdel.php
<?php
$ac = $_GET['lid'];
$con = mysql_connect("127.0.0.1","root","password");
mysql_select_db("babytradeapps");
$sql = "delete from loginacc where LoginID = '$ac'";
if(mysql_query($sql))
{
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
else
{
echo 'fail!';
echo '<meta http-equiv=REFRESH CONTENT=2;url=management.php>';
}
echo mysql_error()
?>