increment/decrement $_SESSION variable when button is click. Hint header() - php

I Initialized a $_SESSION variable = 1 and I want to increment/decrements its value when a link is click. And the links will reload the page then echo the value of the $_SESSION. I was given a hint redired using header() but I still can't figure it how.
<?php
if (isset($_SESSION['count'])) {
$count = $_SESSION['count'];
} else {
$count = '';
}
?>
Increment
Decrement
<?php if (isset($_SESSION['count'])): ?>
<?php echo $count ?>
<?php endif ?>

header("Location: index.php") is a php redirect. In this case if the code above is in the index.php file already, there's no need to redirect the user.
<?php
session_start();
if(!isset($_SESSION['count']) { // first time opening the page
$_SESSION['count'] = 0; // initializing the counter
} else { // counter already have a value
if(isset($_GET['inc'])) { // increasing
echo ++$_SESSION['count']; // no need for extra variable (preincrement to echo immediately)
}
if(isset($_GET['dec'])) { // decreasing
echo --$_SESSION['count']; // no need for extra variable (predecrement to echo immediately)
}
}
?>
Increment
Decrement

<?php
session_start();
if(!isset($_SESSION['count'])
$_SESSION['count'] = 0;
$counter = $_SESSION['count'];
$counter = (int)$counter;
if (isset($_GET['inc'])==TRUE) {
$counter++;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
if (isset($_GET['dec'])==TRUE) {
$counter--;
$_SESSION['count'] = $counter;
header("Location: index.php");
}
?>
Also You may need to cast $counter to int..

Related

If session has value echo it else echo "all"

Update 2
I'll just leave this here for future references. But this is the solution I created with all the help I got here. Thanks!
<script>
function Refresh() {
location.reload();
}
</script>
<?php $number = $_SESSION["page_id"]; ?>
<?php
if (isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo do_shortcode('[RICH_REVIEWS_SHOW category="page" num="all" id="'. $number .'"]');
session_destroy();
echo ('<button class="btn btn-0001" onclick="Refresh()">Show All</button>');
}
else{ echo do_shortcode('[RICH_REVIEWS_SHOW num="all"]'); }
;
?>
Update
So I'm trying to just do a simple echo to see if the session is set using this code:
<?php if(isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo 'Set and not empty, and no undefined index error!');
};?>
But doing this breaks my page, I just get a blank page? How do I check if the session is set? When I do a echo of the session using this code:
<?php echo $_SESSION["page_id"]; ?>
It does output the correct session value?? What am I doing wrong?
I have a sessions saved with PHP and I'm using this so that the page ID from Wordpress is echo-ed in a shortcode do_shortcode('');
This is what my code looks like:
<?php $number = $_SESSION["page_id"]; ?>
<?php echo do_shortcode('[RICH_REVIEWS_SHOW category="page" num="all" id="'. $number .'"]'); ?>
<?php echo do_shortcode_all('[RICH_REVIEWS_SHOW category="page" num="all" id="all"]'); ?>
<?php echo $shortcode ;?>
<?php echo $shortcode_all ;?>
Now, what I would like to do is IF the page_id is not stored in the session it should echo all. So how do I go about this?
I found this code, and I think its something I need... But I'm not that great a programmer/coder...
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
So, if I where to put these two together I would get something like this
<?php
$number = $_SESSION["page_id"];
// Evaluates to true because $var is empty
if (empty($number)) {
echo $shortcode_all ;
}
// Evaluates as true because $var is set
if (isset($number)) {
echo $shortcode ;
}
?>
Am I in the right direction?
Solution
<?php
if (isset($_SESSION['page_id']) && !empty($_SESSION['page_id'])) {
echo('Set and not empty, and no undefined index error!');
};
?>
What am I supposed to feel from the missing (?
If you are using wordpress then you should use the session_start(); in wp-config.php file so please first put in you wp-config.php at top and then check.
<?php
$number = $_SESSION["page_id"];
// Evaluates to true because $var is empty
if (empty($number) || $number=='') {
echo $shortcode_all ;
}else{
echo $shortcode ;
}
?>

storing incremented value in session variable and printing it

Had googled this but maybe I'm not a good googler. My ultimate goal is to have a view more button that will read the next 6 files from a directory but before I do that I need to figure out this problem:
at the top of my index.php i have this:
<?php
if(session_id() == '') {
session_start();
$_SESSION["count"] = 0;
}
?>
lower down I have this:
<?php
function album() {
$_SESSION["count"]=$_SESSION["count"]+10;
echo $_SESSION["count"];
}
?>
when the user clicks a button its supposed to print the session variable + 10 on each click.. so 10 20 30 40 ..ect. But it keeps printing 10, it's not updating.
Always start session at the top of the page like
<?php
session_start();
if(session_id() == '') {
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] += 10;
echo $_SESSION["count"];
}
?>
You need to first do session_start() and then ask for $_SESSION.
<?php
session_start();
if(empty($_SESSION['count'])){
$_SESSION["count"] = 0;
}
function album() {
$_SESSION["count"] = $_SESSION["count"] + 10;
echo 'Count: '.$_SESSION["count"];
}
album();
?>
This I just tested it and it works fine.

How to properly redirect to the same page in php

I am working on something that i want to use in a project.
i am to redirect the current page to itself using php and session. The idea is that:
if my `$_session['insert']= true; then refresh the page to itself;`
Here is the code:
sess_page1.php
session_start();
$_SESSION["insert"] = 1;
$_SESSION["test"] = "Page refreshed";
?>
Click here to go to the next page
sess_page2.php
<?php
session_start();
if (isset($_SESSION["insert"]) && ($_SESSION["insert"]==1)) {
header('location:'.$_SERVER['PHP_SELF']);
print $_SESSION["test"];
}
else
{
echo "Impossible to execute.";
exit();
}
?>
But the page does not redirect to itself...The whole idea is the page should refresh one time.
What i did wrong here? Can somebody help?
Try this:
sess_page1.php
session_start();
$_SESSION["stopper"] = 0;
$_SESSION["insert"] = 1;
$_SESSION["test"] = "Page refreshed";
?>
Click here to go to the next page
sess_page2.php
<?php
session_start();
if (isset($_SESSION["insert"]) && ($_SESSION["insert"]==1) && ($_SESSION["stopper"]==0)) {
$_SESSION['stopper']=1;
header('location:'.$_SERVER['PHP_SELF']);
print $_SESSION["test"];
}
else
{
echo "Impossible to execute.";
exit();
}
?>

How to echo alternatively 2 values on every refresh?

I'm writing PHP code and I have two variables $var1 and $var2. I want a method that helps me to display alternatively on every refresh one of the two values.
For example:
On the first load of page it must display: echo $var1
On the first refresh of page it must display: echo $var2
On the second refresh of page it must display: echo $var1
On the third refresh of page it must display: echo $var2
etc...
For example you can use sessions.
<?php
session_start();
$a = 1;
$b = 2;
if(!isset($_SESSION['variable'])){
$_SESSION['variable'] = true;
}
if($_SESSION['variable']){
echo $a;
}else{
echo $b;
}
$_SESSION['variable'] = !$_SESSION['variable'];
?>
Counting reloads and saving counter to session (https://github.com/Waldz/Examples/blob/master/session/session_counter.php)
<?php
session_start();
if (!isset($_SESSION['timesPageReloaded'])) {
$_SESSION['timesPageReloaded'] = 1;
}
if ($_SESSION['timesPageReloaded']%2 == 1) {
echo 'VAR1 (odd reload)';
} else {
echo 'VAR2 (even reload)';
}
$_SESSION['timesPageReloaded']++;

Why does this undefined error occur when storing the first number to a $_SESSION[] variable?

I'm making a mini shopping cart for my project. Im storing the number of items chosen by the user, I don't understand that when i add one to my session variable I always get this error on the first go
Undefined index: cart_1 in D:\wamp\www\MiniCart\cart.php on line 100
And when I add again or refresh the same page it works fine. Why could this error be coming up? I removed the +=1 from the statement and it worked fine, apparently there is no syntax error too.
Cart.php
<!DOCTYPE>
<html>
<head></head>
<body>
<?php
session_start();
//The page where to jump to after adding/editing cart.
$page = 'mini_cart_index.php';
$link = mysqli_connect("localhost","root","","cart");
if(mysqli_connect_errno())
{
echo "Error:".mysqli_connect_error();
echo "<br/>";
} else {
echo "Connected to SQL<br/>";
}
//==================================================
if(isset($_GET['add']))
{
$obt=$_GET['add'];
$quantity_limit = 'SELECT id,quantity FROM products WHERE id='.mysqli_real_escape_string($link,(int)$_GET['add']);
$quantity = mysqli_query($link,$quantity_limit);
while($quantity_row=mysqli_fetch_assoc($quantity))
{
if($quantity_row['quantity']!=$_SESSION['cart_'.$_GET['add']])
{
$_SESSION['cart_'.$_GET['add']]+='1';
}
}
/*
echo 'id='.$obt.' '.'next<br/>';
echo 'Now storing info into session variable and adding one<br/>';
echo $_SESSION['cart_'.$_GET['add']];
echo '<br/>';
echo 'info stored<br/>';
*/
}
//***************************************************
function products()
{
GLOBAL $link;
$get ="SELECT id,name,description,price FROM products
WHERE quantity > 0 ORDER by id ASC";
if($result=mysqli_query($link,$get))
{
echo "Data Selected to be displayed<br/>";
} else {
echo "Error:".mysqli_error($link);
}
if(mysqli_num_rows($result)==0)
{
echo "There are no products to display!<br/>";
} else {
while($get_row=mysqli_fetch_assoc($result))
{
echo '<hr/><br/>';
echo 'displaying data from database<br/>';
echo '==================================';
echo '<p>'.$get_row['name'].'<br/>'.
$get_row['description'].'<br/>'.
number_format($get_row['price'],2).
' Add'.'</p>';
echo '<hr/><br/>';
}
}
}
echo 'outside'.$_SESSION['cart_1'];
?>
</body>
</html>
Mini_cart_index.php
<?php require 'cart.php';?>
<!DOCTYPE>
<html>
<head>
</head>
<body>
<?php products() ?>
</body>
</html>
That code is filled with SQL injection vulnerabilities, you should use PDO and prepare your statements.
PHP is warning you because it has to read the current value and add to it, but the first time you try to access it doesn't exist.
You could suppress the warning with:
#$_SESSION['cart_'.$_GET['add']]+='1';
A better way to do it though would be checking if it exists first
$name = 'cart_'.$_GET['add'];
if(isset($_SESSION[$name]) {
$_SESSION[$name] = 1;
} else {
$_SESSION[$name] += 1;
}
The problem is caused by the fact that...
$var['abc'] += 1
...is the same as
$var['abc'] = $var['abc'] + 1
So if you've got a clean session and $var['abc'] doesn't exist, you're going to get a warning because you're trying to read a non-existant value in order to add 1 to it.
While it's true that 0 + 1 = 1
...what's actually happening here is undefined + 1 = 1 with a warning.
As other answers have mentioned - to fix the issue, you can explicitly check that the array index exists before trying to increment it.
I'd do that with the ternary operator like this:
$key = 'card_' . $_GET['add'];
$_SESSION[$key] = (isset($_SESSION[$key]) ? $_SESSION[$key] : 0) + 1;
This is effectively saying
$val = ($val if it exists, otherwise 0) + 1;
Change your if statement to check if it's empty too:
if (!isset($_SESSION['cart_'.$_GET['add']])) {
$_SESSION['cart_'.$_GET['add']] = 1;
} elseif ($quantity_row['quantity'] != $_SESSION['cart_'.$_GET['add']]) {
$_SESSION['cart_'.$_GET['add']] += 1;
}

Categories