CodeIgniter set multidimantional session value - php

I want to set a value in a Codeigniter session array, something like:
$this->session->userdata['xxx']['yyy'] = $some_value;
But it didn't work. Also, I've tried:
$this->session->sess_write();
But that did not work either for me. Does anyone know how I can assign a value to this kind of session?

You can set multi dimensional array with this example.
$row => array(
'basket_id'=>'1',
'order_id'=>'1',
'cus_id'=>$cusid,
'product_id'=>$pro_id,
'bas_quantity'=>1
)
$cart = array($row);
$this->session->set_userdata('cart',$cart);

You can set multi-dimensional array as below.
$this->session->set_userdata(array("index_1"=>array("val1","val2","val3")));
Then you can use
$sess_data = $this->session->userdata("index_1");
echo $sess_data[0];
echo $sess_data[1];
echo $sess_data[2];

You cannot directly unset specific value of multidimensional array in session of codeingiter. You have to take all session value to variable. Unset the specific value and again set the variable in session as shown below:
$items_session = $this->session->userdata('item_names');
unset($items_session[$key][$app_no]);
$this->session->set_userdata('item_names',$items_session);
Hope this will help.

Related

Array_push pushes invisible element, and only works on second push

I had a problem with my array_push, that i noticed.
So what i'm doing.:
I have a site, where there are some buttons with a specific value.
Each value is getting fetched from a database.
I have a session called test, that get's converted to an array(to store multiple in the same array)
Everytime one of the buttons are clicked, the value for that specific button, is getting pushed to the array.
But, i can ONLY see that it has been pushed at the second try.
[test] => Array( [0] => 21304 )
This is what i see, after second try. But my array count, says that there are 2 elements, in that array.
Here is my code:
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
$array_merge = array_push($_SESSION['test'], $_POST['process']);
}
}
The $_POST['process'] is the button with the unique value.
Can somebody maybe see what I'm doing wrong here?
Kind regards
You are only adding to the $_SESSION['test'] array if $_SESSION['test'] was not previously set.
So you need to always add an occurance to the session array and only initialise the session array if it was not previously set
session_start();
// ...
if(isset($_POST['process'])) {
if(!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
$_SESSION['test'][] = $_POST['process'];
}
NOTE from the manual
If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function.

Storing variables in SESSION array

I have a variable which changes its value in every ajax request.
What I want to accomplish is to have a session array $_SESSION["tmp_arr"] and fill it with the values of this same variable. I dont want to overwrite the value of the $_SESSION variable, but append it in a array.
Which is the correct way to accomplish that?
If there is no such element in _SESSION or if it's not an array create a new one with the first/initial value. Otherwise append the new value to the existing array.
session_start();
[...]
if ( !isset($_SESSION["tmp_arr"]) || !is_array($_SESSION["tmp_arr"]) ) {
$_SESSION["tmp_arr"] = array( $newValue );
}
else {
$_SESSION["tmp_arr"][] = $newValue;
}

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);

PHP - Save value AND name using $_POST

I'm currently using the following format to save a value from an HTML form $item_name=$_POST['item_name'];
This saves the value, but how to I also save the name attribute in a variable?
Thanks in advance!
Assuming you want to store each element of $_POST variable as a key-value pair, then you can try:
$var = array();
foreach($_POST as $key => $val) {
$var[$key] = $val;
}
I'm saving a lot of values and want to avoid typing each one out.
Please, make your mind first.
Global variables are intended to be typed by hand.
If you want some automated processing - just keep them in a form of array.
Looks like rdt.exe's answer is what you're looking for.
maye you noticed you have to use the name to access the $_POST-array and get the value. if you want to store the name in a variable, too, just do:
$item_name_name = 'item_name';
$item_name_value = $_POST[$item_name_name];
you could also use some kind of loop to dynamically create variables with the according names like this:
foreach( $_POST as $name => $value ){
$$name = $value;
}
both ways are some kind of unnecessary and useless in my opinion, but you havn't stated what exactly you're trying to achive - so maybe this helps.
An alternative approach:
$keysarray = array_keys ( $_POST);
print_r( $keysarray);
This will give you all the keys in array
The function you are looking for is called extract.
This will create variables for all the $key=>$val pairs in the array.
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound');
export($_EXAMPLE);
echo $bird; # prints "chicken"
echo $dog; # prints "greyhound"
Watch out though - this is a huge security risk. So are the solutions described in some of the other answers.
The problem with doing something like this is that a user can tamper with the POST data, and set parameters other than the ones she is supposed to set. If they set variables that are actually variable names in your application, those variables can be overwritten.
$is_admin = false;
$_EXAMPLE = array('bird' => 'chicken', 'dog' => 'greyhound', 'is_admin' => 'true');
export($_EXAMPLE);
if ($is_admin) { # this will now evaluate to true.
# do sensitive stuff...
}

change last key name from array in php

i want to be able to change the last key from array
i try with this function i made:
function getlastimage($newkey){
$arr = $_SESSION['files'];
$oldkey = array_pop(array_keys($arr));
$arr[$newkey] = $arr[$oldkey];
unset($arr[$oldkey]);
$_SESSION['files'] = $arr;
$results = end($arr);
print_r($arr);
}
if i call the function getlastimage('newkey') it change the key!but after if i print the $_SESSION the key is not changed? why this?
When you set $arr = $_SESSION['files'], you are actually making a copy of $_SESSION['files']. Everything you do to $arr is not done to the original.
Try this:
$arr =& $_SESSION['files'];
Note the ampersand after the equals sign. That will make $arr a reference to $_SESSION['files'], and your updates to $arr will affect $_SESSION['files'] as well, since they both reference the same content.
The other solution is of course to just copy the array back by putting $_SESSION['files'] = $arr; at the end of your function.
Wow, your code is a mess!
1) You're setting $_SESSION in a new array. In order for your changes to take affect, you'll need to set back to your original $_SESSION array, otherwise your new array will just be forgotten.
2) It would be easier to simply array_pop() to get the last element and set it to the new key, rather than wasting the time to fetch all the keys and pop the last key off, then fetch the value from the array again. The old key value is worthless.
try update the session
$_SESSION['files'] = $arr;

Categories