Cookie not save in foreach - php

People
I am trying to build a shopping cart, So i will have to pass the id , quantity and location_id to the function. In the function, i will look at the id and location_id passed in, if similar id and location_id is found. I will +1 to the item. However, if i use the function in array, it is not working.
Below is another function i built to test the variables pass to function within foreach.
But is does not say the first variable i passed in. it will only save the latest variable.
Below is my function codes :
static public function test($id , $per_min, $location_id_cart = 0){
echo $new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
var_dump($_COOKIE);
}
Below is my codes calling the function :
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
My result :
'cart_item' => string '125-10-789' (length=10)
My expected result :
'cart_item' => string '125-5-636,125-10-789'
if i refresh my page, the result i get is this :
'cart_item' => string '125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789,125-10-789'
The cookie will only save the latest value given in the array. it does not save 125-5-636 to the cookie.
Why? can anyone help me on this please? Thank you!

try the following code:
static public function test($id , $per_min, $location_id_cart = 0){
$new_cart = $id.'-'.$per_min.'-'.$location_id_cart;
if(isset($_COOKIE['cart_item'])){
$last = $_COOKIE['cart_item'];
$testing = $last.','.$new_cart;
}else{
$testing = $new_cart;
}
$set = setcookie("cart_item", $testing, time()+3600);
//This line deals with adding to the cookie while the script is running
$_COOKIE['cart_item'] = $testing;
//var_dump($_COOKIE);
}
I have a feeling that the $_COOKIE array isn't being updated when you use setcookie(), this is why we update it manually with the line below it.
Also I'd remove the var_dump() call, along with echoing the $new_cart variable, as this will stop setcookie() from working. Instead, I would put it at the bottom of your calling code:
$id = 125;
$multi_location = array(636 , 789);
$multi_quantity = array();
$multi_quantity[636] = 5;
$multi_quantity[789] = 10;
$array_key = array_keys($multi_quantity);
foreach($array_key as $o){
if(!in_array($o , $multi_location)){
unset($multi_quantity[$o]);
}
}
$count = 0;
foreach($multi_location as $i){
ZCart::test($id , $multi_quantity[$i], $i);
}
var_dump($_COOKIE);
If you are implementing a shopping cart, I'd strongly recommend using sessions, which allow you to store the sensitive stuff on the server side away from harm and are in my experience much easier to work with than cookies!
Another option would be to store the user's cart in a database and then if they aren't logged in link to that cart with an ID stored in a cookie. This would allow the cart to stay around if the user closes their browser but keeps the secure stuff from the cookie. I hope this makes sense!

because you are not using array or different variable. Every time you call function in loop, It updates value of cart_item.It doesnot store value in different variables.

Related

how to store return value of a function in session array in php

$tsal[] = $obj->totalsal();
$_SESSION['totalsal'] = $tsal;
for($i=0; $i<count($tsal); $i++)
{
echo $tsal[$i];
}
Is this the right way to store value that is returned from a function in an array using session?
If you want to use session you have to always add session_start()
Then you can access session variables.
If you want to iterate through array it is better to use foreach loop instead of for
Also this line $tsal[]=$obj->totalsal(); creates something like this
$tsal = [0 => $obj->totalsal()];
It is pointless, just do: $tsal = $obj->totalsal();
$tsal = $obj->totalsal();
$_SESSION['totalsal'] = $tsal;
foreach ($tsal as $tsalElement) {
echo $tsalElement;
}
Yes, you can use $_SESSION to store data in the PHP-session. However you need to first initialize/start the session in order to get this working. Use start_session() on top of every script you want to store/access session-data. For more infos look here
<?php
session_start (); // now session data is available
$_SESSION['totalsal'] = $tsal;
...
?>
On some other script you can then access your data by
<?php
session_start ();
for ($i = 0; $i < count ($_SESSION['totalsal']); $i++)
echo $_SESSION['totalsal'][$i];
...
?>

Unset array element and reseting array values in PHP

So I have 2 files. In file 1 I have a table and there I randomly select some fields and store (store in session) them in an array of 2D arrays. When I click on the cell I send this data to my file 2 where I want to check if I clicked on a randomly selected array or not and if I did, I want to remove this 2D array from an main array.
But as soon as I click on one of the selected arrays, the array crashes.
File 1 PHP stuff immportant for this:
session_start();
$_SESSION['arrays'] = $stack ;
File 2 PHP:
session_start();
if (isset($_SESSION['arrays'])) {
$stack = $_SESSION['arrays'];
for ($i = 0; $i< count($stack);$i++){
if($cooridnates == $stack[$i]){
unset($stack[$i]);
array_values($stack);
$i--;
$Result = true;
break;
}
}
$_SESSION['arrays'] = $stack ;
I am suspecting the error might be in 2 things:
count($stack) used, but I don't believe this is the main reason.
The way I store session.
I have tried using manuals from W3Schools and official PHP website and also SOF, but with no use.
But still, I am not sure if the array_values() and unset() is working correctly since the thing chrashes and I can't test it correctly.
I would appreciate any tips.
You need to assign the result of array_values($stack); back to the $stack variable.
$stack = array_values($stack);
There's also no need to use $i-- when you do this, since you're breaking out of the loop after you find a match.
Instead of a loop, you can use array_search():
$pos = array_search($coordinates, $stack);
if ($pos !=== false) {
unset $stack[$pos];
$Result = true;
$stack = array_values($stack);
$_SESSION['arrays'] = $stack;
}
you can do this like that by using foreach loop:
session_start();
if (!empty($_SESSION['arrays'])) {
foreach( $_SESSION['arrays'] as $key => $val){
if($cooridnates == $val){
unset($_SESSION['arrays'][$key]); // if you want this removed value then assign it a variable before unsetting the array
$Result = true;
break;
}
}
}

PHP array limit? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
friends i am new in php. I am playing with array. So i am unable to solve one login using array. In this program i want to show array limit. I have number of data it's come form Database. But i want to show limit data like ( 10 posts only ). I know the MYSQL query to show limit data. But i am trying with array. So please help to solve this logic thanks.
here is the code.
$reverse = array_reverse($showpost, true);
foreach ($reverse as $key=>$postvalue) {
$latestpost = explode(',', $postvalue['postcategory']);
if (in_array("3", $latestpost)) {
// result here...
}
}
I have save the category this format (1,2,3,4,5,6). That's why I have used explode() function.
My DataBase fields name are ( post_id, postname, postcategory, postdisc,).
Not sure if I've understood the problem correctly but I think it maybe related to this link
$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3); // returns "a", "b", and "c"
You can use array_chunk() function
CODE:
<?php
$reverse = array_reverse($showpost, true);
foreach($reverse as $key=>$postvalue){
$latestpost = explode(',', $postvalue['postcategory']);
$chunks = array_chunk($latestpost, 3);
print_r($chunks);
}
?>
If you're only wanting to show 10 rows, and result here... is where each post is show, then something like this may work:
$postsShown = 0;
$reverse = array_reverse($showpost, true);
foreach ($reverse as $key => $postvalue) {
if ($postsShown >= 10) {
break;
}
$latestpost = explode(',', $postvalue['postcategory']);
if (in_array("3", $latestpost)) {
// result here...
$postsShown++;
}
}
All this does is count how many posts are shown using the $postsShown variable, and increments it when a new post is shown. When this variable reaches 10 (IE, 10 posts are shown), the loop will be terminated using the break command.
maybe you can use a session variable to save few attempts the user used to log, and you validate it in the server.
with this code you can create a session variable:
session_start();
$_SESSION['name_of_my_variable'] = 'value of my session variable';
and for example each time the user tries to log you can increase the value of your counter in the session variable:
the first time you needs create the session variable:
session_start();
$_SESSION['log_counter'] = 1;
and the next attempts you increment the counter like this:
session_start();
$log_counter = $_SESSION['log_counter'];
$log_counter++;
$_SESSION['log_counter'] = $log_counter;
check if the user already reached the limit:
session_start();
if ($_SESSION['log_counter'] == 10)
{
echo "Limit reached";
}
This is the final code:
// init session variables
session_start();
// Check if exist the session variable
if (isset($_SESSION['log_counter']))
{
// Enter here if the session variable exist
// check if the log_counter is equals to the limit
if ($_SESSION['log_counter'] == 10)
{
echo "Limit reached";
}else
{
// increase the counter
$log_counter = $_SESSION['log_counter'];
// this increate 1 more to the log_counter session variable
$log_counter++;
// here we save the new log_counter value
$_SESSION['log_counter'] = $log_counter;
}
}else
{
// Enter here if not exist the session variable
// this create the log_counter session variable
$_SESSION['log_counter'] = 1;
}

i can`t store session value passing through jquery ajax. in codeigniter php framework

I have a problem storing session value;
I am not able to increment the session count variable
via the AJAX Jquery call with some value passing
to function, also my previously set array which stores the session is change with a new one.
What is the problem here:
1>when i use one controller function
startOnlineTest($testid=0)
i set session countnew as 0
$this->session->set_userdata('countnew',0);
and in view i use jquery to pass data to other function of same controller
public function ResponseOnline($qid,$response)
using change effect of jquery
echo "[removed]$(document).ready(function(){";
foreach($question['childQuestion'] as $q=>$aq){ //
echo "\$(\"input:radio[name=qid-$q]\").live('change',function(){
var sr=\$(\"input:radio[name=qid-$q]:checked\").map(function() {
return $(this).val();
}).get().join();
var qid = \$(\"input:radio[name=qid-$q]\").attr(\"qaid\");
"; echo "\$.get('"; echo base_url();echo "testpapers/ResponseOnline/'+qid+'/'+sr,{},function(data)
{\$('#res').html(data)});
});";}
echo"});[removed]" ;// this script is working fine
now the problem is this i get the session value overwrite by the current one although i
use array my code for ResponseOnline
is
public function ResponseOnline($qid,$response)
{
echo "this" .$this->session->userdata('countnew'); // this is not echo as set above by function startOnlineTest($testid=0)[/color]
i set session countnew as
$this->session->set_userdata('countnew',0)
echo $d=$qid; // i know its no use but to save time as tested on $d
$s=$response;
if($this->session->userdata('countnew')==0) // algo for this function i check the
//countnew session varaible if 0 do this
{
$sc=$this->session->userdata('countnew'); // store the countnew variable
echo $sc=$sc+1; // increment the counter variable
$this->session->set_userdata('countnew',$sc); // store it in session
echo "this is incrementes session value";
echo $this->session->userdata('countnew');
$r2[$d]=$s; // store array value $r2 with key $d and value $s
$this->session->set_userdata('res',$r2); //set this array value in session
}
else{ // if session countnew!=0 then do this
$r2=$this->session->userdata('res'); // first store $r2 as array return from session
$r2[$d]=$s; //then add value to this array
$this->session->set_userdata('res',$r2); // storing this array to session
}
echo '<pre>';
print_r($r2); // printing the array
}
i get the result for say for first call is fine but for second call my value is overwrite session show Array([32323]=>23)) if i pass function (32323,23) if i pass (33,42)
i get Array([33]=>42) my old value is destroyed.
You should just probably use regular sessions in php because sessions in codeigniter will only allow you to store a single item.
Something like this:
$_SESSION['item'][] = $array;
Or maybe you could still use CodeIgniter sessions by doing something like this:
$items = $this->session->userdata('items');
array_push($items, $new_item);
$this->session->set_userdata('items', $items);
If you want to define the keys as well:
$items = $this->session->userdata('items');
$items['your_key'] = $new_item;
$this->session->set_userdata('items', $items);

Cannot add new values to $_SESSION

I've a very strange problem with a session variable.
This var is an associative array. I create this in a page (page A) with a lot of filterable items. I save filters in a session var
$_SESSION['filter'] = Array ( 'm' => 'acrylic', 'a' => 'P', 'c' => 1960 );
the user can go to a detail page (page B) but here I have
$_SESSION['filter'] = Array ( 'm' => 'acrylic', 'a' => 'P');
the strange is that when I go i the detail page I miss the last item in the associative array
so I can't go back with the right filter info.
I build the session var in this function, the options are passed in the URL example: http://www.web.com/artworks/a-P/c-1960/o-private+collection
the argument $args with this URL will be this array('a-P', 'c-1960', 'o-private+collection')
private function filter($args){
// options
$f = array('a','c','u','t','m','o');
$a = array();
foreach($args as $i){
$t = explode('-', $i);
if (in_array($t[0], $f)){
$a[$t[0]] = urldecode($t[1]);
$this->suffix .= '/'.$i;
}
else if(is_numeric($i))
$a['pp'] = intval($i);
}
$_SESSION['filter'] = $a;
return $a;
}
I call this in page A, In the page B I don't call this function the only interaction is
if (isset($_SESSION['filter'])){
print_r($_SESSION);
...
Someone can help me?
Thanks
You have to call session_start somewhere in your script before adding new values into $_SESSION, otherwise they will not persist. Do you do that?
I don't know exactly but try with giving last varible value in quotes.

Categories