HI I wanted to know how to restart a session in php. When I use the code given below in one of my pages it would work for the 1st time. When I refresh the page the previous session continues. So how can I start a new session when the page reloads?Thanks for the quick response.INCLUDED WHOLE CODE TO MAKE THINGS CLEAR
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Shopping Cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="products-wrapper">
<h1>Products</h1>
<div class="products">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$results = $mysqli->query("SELECT * FROM shop ORDER BY product_code ASC");
if ($results) {
//fetch results set as object and output HTML
while($obj = $results->fetch_object())
{
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-info">';
echo 'Price '.$currency.$obj->price.' | ';
echo 'Qty <input type="text" name="product_qty" value="0" size="3" />';
echo '<button class="add_to_cart">Add To Cart</button>';
echo '</div></div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
}
}
?>
</div>
<div class="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["shop"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["shop"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code"></div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart">Empty Cart</span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</div>
</body>
</html>
You may use session_destroy function in the end of your file.
<?php
session_start();
include_once("config.php");
/*your code*/
session_destroy();
?>
session_destroy — Destroys all data registered to a session
bool session_destroy ( void )
http://php.net/manual/en/function.session-destroy.php
You need to use session_destroy(); to destry a session and then you can start a new one
try to remove session first and start again
if(session_id() != '' || isset($_SESSION)) {
session_destroy();
session_start();
}
else {
session_start();
}
You have to destroy the session after your event.
<?php
session_start();
include_once("config.php");
//after doing your task with the session variable destroy session
session_destroy();
?>
<?php
#session_destroy(); // destroy session if exists
session_start();
include_once("config.php");
?>
UPDATE 2 :
<?php
if(isset($_SESSION))
{
session_destroy(); // destroy session if exists
}
session_start();
include_once("config.php");
?>
UPDATE 3 :
If you want to unset only $_SESSION['shop'] after using it
if(isset($_SESSION["shop"]))
{
// your code
unset($_SESSION['shop']); // unset your session after using it
}else{
echo 'Your Cart is empty';
}
Related
This is the entirety of the code that I have on this page. I've linked to the server connection, which works. Can't figure out what's wrong. Some input would be appreciated.
<?php
session_start();
require_once("account-management/db_connect.php");
if (isset($_SESSION['user_lister_id']) && ($_SESSION['email'])) {
echo '<section class="topnavbar">';
echo '<div id="top-login">';
echo 'Listing Profile / Account Settings / Case Requests';
echo '</div>';
echo '</section>';
} else {
echo '<section class="topnavbar">';
echo '<div id="top-register">';
echo 'Client Register / Lister Register';
echo '</div>';
echo '<div id="top-login">';
echo 'Client Login / Lister Login';
echo '</div>';
echo '</section>';
}
?>
<section class="header-grid">
<img src="../images/Logo.png" width="120" />
<div id="ad-field">This content coming soon!</div>
</section>
I am learning PHP and am stuck right now. In a while loop, all the to-do items are displayed. Each of these elements has a delete button and a check button. The delete button works in every element, but the check button only works in the first one. The check button is to be used to check off an element. When the check button is pressed, an error message is displayed that this element could not be deleted. Only in the first element of course not. I can't find the error.
I suspect there is something wrong with the in the index
<?php
$todos = $conn->query("SELECT * FROM todos ORDER BY id DESC");
?>
<div class="show-todo-section">
<?php if($todos->rowCount() <= 0){ ?>
<div class="todo-item">
<div class="empty">
<img src="img/f.png" width="100%" />
<img src="img/Ellipsis.gif" width="80px">
</div>
</div>
<?php } ?>
<?php while($todo = $todos->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="todo-item">
<form action="app/checked.php" method="POST">
<button class="check-box" value="<?php echo $todo['id']; ?>" name='checked' type="submit">Check</button>
</form>
<form action="app/delete.php" method="POST">
<button class="remove-to-do" value="<?php echo $todo['id']; ?>" name='delete' type="submit">x</button>
</from>
<?php if($todo['checked']){ ?>
<h2 class="checked"><?php echo $todo['title'] ?></h2>
<?php }else { ?>
<h2><?php echo $todo['title'] ?></h2>
<?php } ?>
<small>created: <?php echo $todo['date_time'] ?></small>
<?php for ($i = 1; $i <= $todo['coins']; $i++) {
echo "<img class='coins' src='img/coin.gif' width='40px' />";
} ?>
</div>
<?php } ?>
</div>
the checked.php
<?php
if (isset($_POST['checked'])) {
require '../db_conn.php';
$id = $_POST['checked'];
if(empty($id)){
header("Location: ../index.php?mess=errorChecked". $id);
}else{
$todos = $conn->prepare("SELECT id, checked FROM todos WHERE id=?");
$todos->execute([$id]);
$todo = $todos->fetch();
$uId = $todo['id'];
$checked = $todo['checked'];
$uChecked = $checked ? 0 : 1;
$res = $conn->query("UPDATE todos SET checked=$uChecked WHERE id=$uId");
header("Location: ../index.php?mess=successChecked");
$conn = null;
exit();
}
} else{
header("Location: ../index.php?mess=errorChecked");
}
Im trying to insert data from sessions into a database using an insert statement. I have data passed from a login screen which is stored in a session variable called "login_user". I also have a session called "books" which stores multiple variables such as the ISBN number, Title and Price of a book.
I have the following code:
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View shopping cart</title>
<link href="style/style.css" rel="stylesheet" type="text/css"></head>
<body>
<br>
<div id="books-wrapper">
<!-- #content to center the menu -->
<div id="content">
<!-- This is the actual menu -->
<ul id="darkmenu">
<li>Home</li>
<li>Catalogue</li>
<li>Search</li>
<li>Cart</li>
<li>Orders</li>
</ul>
<div id = "welcome" >
Welcome, <?=$_SESSION['login_user']?>! <br> Logout
</div>
</div>
<br><br>
<h1 id = "mainHeader" >View Cart</h1>
<br>
<div class="view-cart">
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_SESSION["books"]))
{
if(isset($_POST['submit_btn']) ){
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, '$obj->Title', '$cart_itm['quantity']', '$total', '$ISBN', '$_SESSION['login_user']');";
}else {
$total = 0;
echo '<form method="post" action="">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["books"] as $cart_itm)
{
$ISBN = $cart_itm["ISBN"];
$results = $mysqli->query("SELECT Title,BookDesc,Price FROM books WHERE ISBN='$ISBN'");
$obj = $results->fetch_object();
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-Price">'.$currency.$obj->Price.'</div>';
echo '<div class="book-info">';
echo '<h3>'.$obj->Title.' (ISBN :'.$ISBN.')</h3> ';
echo '<div class="p-quantity">Quantity : '.$cart_itm["quantity"].'</div>';
echo '<div>'.$obj->BookDesc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["Price"]*$cart_itm["quantity"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->Title.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$ISBN.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->BookDesc.'" />';
echo '<input type="hidden" name="item_quantity['.$cart_items.']" value="'.$cart_itm["quantity"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '<button name="sumbit_btn" class="save_order">Save Order</button>';
echo '</form>';
}else{
echo 'Your Cart is empty';
}
}
?>
</div>
</div>
</body>
</html>
However my insert statement doesnt seem to work.
I get the ( ! ) Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) on line 43 which is the insert statement
I do have a page called Catalogue where the variables are instantiated but these are then passed onto the view cart page which is above.
Any idea whats wrong with the statement?
replace line 43 with
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, '{$obj->Title}', '{$cart_itm['quantity']}', '{$total}', '{$ISBN}', '{$_SESSION['login_user']}');";
And remember to sanitize your variables!
just replace 43 line with the below code
$sql = "INSERT INTO `orders` (`OrderNo`, `BookName`, `Quantity`, `TotalPrice`, `ISBN`, `StudentID`) VALUES (NULL, $obj->Title, $cart_itm['quantity'], $total, $ISBN, $_SESSION['login_user']);";
let me know its working or not?.
I would greatly enjoy knowing how to separate the results of my query based on the "season" using PHP only. The products should be placed in separate divs according to what season they are for. I would also like to do this in the most efficient way possible. I have thought about his for some time and have failed both in a solution and in finding someone else's similar results on the internet. Please ignore the jquery, it is a leftover for something I may or may not use.
<?php
session_start();
include_once("config.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>Shop</title>
<link rel="stylesheet" type="text/css" href="style/main.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0
/jquery.min.js"></script>
<script type="text/javascript" src="script/jquery.simplyscroll.min.js"></script>
<script type="text/javascript">
(function($) {
$(function() {
$("#scroller").simplyScroll();
});
})(jQuery);
</script>
</head>
<body>
<div id="container">
<div id="header">
<div id="menu">
<ul>
<li>Home</li>
<li>About</li>
<li>Shop</li>
<li>Contact</li>
</ul>
</div>
</div>
<div id="content">
<?php
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
//$results = $db->query('SELECT id, name, thumb, description, price, season FROM products
BY season ASC');
foreach($db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC') as $results){
if ($results) {
//output results from database
$last_season = 1;
echo '<div class="products">';
while($obj = $results->fetch_object())
{
if ($last_season != $obj->season){
echo '</div><div class="products">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button
class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>';
}
}
?>
<div id="shopping-cart">
<h2>Your Shopping Cart</h2>
<?php
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<ol>';
foreach ($_SESSION["products"] as $cart_itm)
{
echo '<li class="cart-itm">';
echo '<span class="remove-itm"><a href="cart_update.php?removep='.$cart_itm["code"].'&
return_url='.$current_url.'">×</a></span>';
echo '<h3>'.$cart_itm["name"].'</h3>';
echo '<div class="p-code">P code : '.$cart_itm["code"].'</div>';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div class="p-price">Price :'.$currency.$cart_itm["price"].'</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
}
echo '</ol>';
echo '<span class="check-out-txt"><strong>Total : '.$currency.$total.'</strong> Check-out!</span>';
echo '<span class="empty-cart"><a href="cart_update.php?emptycart=1&
return_url='.$current_url.'">Empty Cart</a></span>';
}else{
echo 'Your Cart is empty';
}
?>
</div>
</div>
<div id="footer">Footer goes here.</div>
</div>
</body>
</html>
I am getting an error on line 44, which is the start of the "foreach" statement. I am again at a loss. Thank you a ton for your help so far. If I can get this working, with help of course, I will be extremely excited and in your debt.
Here's a loop that will create a new div each time the season changes in a new row. You will need to change the query to order the results by season, e.g.
ORDER BY season ASC
Here's the loop:
if ($results) {
//output results from database
$last_season = 1; //initial value
echo '<div class="season">'; //opens first season div
while($obj = $results->fetch_object()){
if ($last_season != $obj->season){
echo '</div><div class="season">';
}
echo '<div class="product">';
echo '<form method="post" action="cart_update.php">';
echo '<div class="product-thumb"><img src="image/'.$obj->product_img_name.'"></div>';
echo '<div class="product-content"><h3>'.$obj->product_name.'</h3>';
echo '<div class="product-desc">'.$obj->product_desc.'</div>';
echo '<div class="product-info">Price '.$currency.$obj->price.' <button class="add_to_cart">Add To Cart</button></div>';
echo '</div>';
echo '<input type="hidden" name="product_code" value="'.$obj->product_code.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
echo '</div>';
$last_season = $obj->season;
}
echo '</div>'; //closes final season div
}
Regarding the line 44 error in the foreach, I believe what you want there instead of a foreach is simply:
$results = $db->query('SELECT id, name, thumb, description, price FROM products BY season
ASC'); //remember to remove the closing bracket of the foreach
I am trying to paginate my PHP page by ten results per page. Currently the page shows all results at once. I did look up some tutorials on pagination but I cannot seem to figure out how to implement them into the current PHP page. The PHP page is called view_cart.php and it essentially retrieves the cached products that were added by the user via a shopping cart page and displays them on this page. I am just looking for a few hints to point me in the right direction, not for someone to do my work for me.
This is the view_cart.php page code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<?php
session_start();
include_once("config.php");
if(isset($_SESSION["products"]))
{
$total = 0;
echo '<form method="post" action="PAYMENT-GATEWAY">';
echo '<ul>';
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm)
{
$product_code = $cart_itm["code"];
$queryy = "SELECT TOP 1 product_name,product_desc, price FROM products WHERE product_code='$product_code'";
$results = mssql_query($queryy, $mysqli);
$obj = mssql_fetch_object($results);
echo '<li class="cart-itm">';
echo '<span class="remove-itm">×</span>';
echo '<div class="p-price">'.$currency.$obj->price.'</div>';
echo '<div class="product-info">';
echo '<h3>'.$obj->product_name.' (Code :'.$product_code.')</h3> ';
echo '<div class="p-qty">Qty : '.$cart_itm["qty"].'</div>';
echo '<div>'.$obj->product_desc.'</div>';
echo '</div>';
echo '</li>';
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
echo '<input type="hidden" name="item_name['.$cart_items.']" value="'.$obj->product_name.'" />';
echo '<input type="hidden" name="item_code['.$cart_items.']" value="'.$product_code.'" />';
echo '<input type="hidden" name="item_desc['.$cart_items.']" value="'.$obj->product_desc.'" />';
echo '<input type="hidden" name="item_qty['.$cart_items.']" value="'.$cart_itm["qty"].'" />';
$cart_items ++;
}
echo '</ul>';
echo '<span class="check-out-txt">';
echo '<strong>Total : '.$currency.$total.'</strong> ';
echo '</span>';
echo '</form>';
echo 'Checkout';
}else{
echo 'Your Cart is empty';
}
?>
<?php
date_default_timezone_set('America/Edmonton');
?>
<?php echo date("D M d, Y G:i a"); ?>
</body>
</html>
This is the config.php page code:
<?php
$mysqli = mssql_connect('gd','Gad','Rdgaf!');
$objConnectee = mssql_select_db('Gdaddf',$mysqli );
?>
Thank you for any help. All help is appreciated.
You will have url parameters: start and count.
Use them in the sql query, like LIMIT $_GET['start'], $_GET['count']
The last thing is to render links to the "Next" and "Previous" page. (and to "First", "Last", 1,2,3,4....). Those links will include parameters start and count.
For example, the "Next" link will contain url with parameters:
"view_cart.php?start=" . ($_GET['start'] + $_GET['count']) . "&count=" . $_GET['count']
Beware of the total record count to not overflow.