session variable name as a variable? - php

I try to make a session variable where the session variable name should be diffrent, and therefore i make the session variable name a variable name:
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
$_SESSION[$num] = $vareInfo;
$_SESSION[$pris] = "hukabuka";
but i dosen't work, i just changeching the the other sessioen to the new value?
it output this:
Array ( [vareNummer] => 182162
[vareNavn] => Solsikke
[varePris] => 120
[vareBillede] => 63c7cba6cac6d7.24544415.jpg
[vareAntal] => 1
)
and next time i run it it changing it instead of making a new

To prevent that your session gets overwritten add a check if the session already exists.
That way it only gets created once for each unique $num
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
if(!isset($_SESSION[$num])){
$_SESSION[$num] = $vareInfo;
}
if(!isset($_SESSION[$pris])){
$_SESSION[$pris] = "hukabuka";
}

An example how this can be made to work (using PHP 8.2):
my_form.html:
<form action="do_stuff.php" method="POST">
<input id="data1" name="data1" type="text">
<input id="data2" name="data2" type="text">
<input type="submit" value="Do">
</form>
do_stuff.php:
<?php
session_start();
$nummer = $_POST['data1'];
$num = $nummer;
$pris = $_POST['data2'];
$vareInfo = array(
"vareNummer" => "$nummer",
"varePris" => $pris
);
$_SESSION['my_data'][$num] = $vareInfo;
$_SESSION['my_data'][$pris] = "hukabuka";
// or, the session variables can be set using a prefix:
//$_SESSION['my_data_' . $num] = $vareInfo;
?>
EDIT ADD:
An example session data from posting twice from the form using two unique data1 values would be as shown below. The values are 1234 and 7890.
Array (
[my_data] =>
Array (
[1234] => Array ( [vareNummer] => 1234 [varePris] => 55 )
[55] => hukabuka
[7890] => Array ( [vareNummer] => 7890 [varePris] => 99 )
[99] => hukabuka
)
)

Check the session with that variable, if already set with that index then do not over write the session value
you can use either isset or !empty in php
<?php
$nummer = $_POST['nummer'];
$num = $nummer;
$vareInfo = array(
"vareNummer" => "$nummer",
"vareNavn" => "$vare",
"varePris" => $pris,
"vareBillede" => $VarBillede,
"vareAntal" => $antal
);
if(!empty($_SSESSION[$num])) {
$_SESSION[$num] = $vareInfo;
}
if(!empty($_SESSION[$pris])) {
$_SESSION[$pris] = "hukabuka";
}
?>

Related

How can i remove integer index from array

How can i access the ID value without having to use the index?
in my code i do this ( $array[0]['data']['ID'] ) to access the ID value, i have many users and having to access them individually by the integer index is time consuming.
I prefer not to use a foreach loop because i my code i make calls to a remote API and it will query the API for each user which kills performane.
If i can convert the current array to one without the index that would be great and just access the ID value through ( $array['data']['ID'] ).
[0] => Array ( [data] => Array ( [ID] => 370
[1] => Array ( [data] => Array ( [ID] => 405
I found that the code below lags my page load tremendously:
foreach ($search_users as $k => $user):
if (!empty($street[0])) {
$db = prettyAddress(get_user_meta($user->ID, 'company_address', true));
$match = matchAddress($formattedAddress, $db, count($street));
if ($match == false)
unset($search_users[$k]);
}
endforeach;
It is referenced in my question here:
Why does my foreach take forever to load
$location = !empty($_POST['saddress']) ? $_POST['saddress'] : "NA";
$display = false;
if ($location != "NA")
$display = true;
global $wpdb;
$location = $_POST['saddress'];
$street = explode(',', $location);
$cat = $_GET['specializingin'];
$args = array(
'meta_query' => array(
array(
'key' => 'scategory',
'value' => $_GET['specializingin'],
'compare' => 'LIKE'
),
array(
'key' => 'specialties',
'value' => ($_GET['specialitiesin'] == 'All Specialties' ? '' : $_GET['specialitiesin']),
'compare' => 'LIKE'
),
),
);
$search_users = get_users($args);
$formattedAddress = prettyAddress($location);
You can assign a variable to the current element of the array:
$current = $array[0];
Then you can access
$current['data']['ID'];
If you need to be able to modify the array using this, you should use a reference:
$current =& $array[0];
you can do this in a loop:
foreach ($array as $current) {
echo $current['data']['ID'];
}

how to display dynamic array values to view from model in codeigniter

here is my model code:
foreach ($query->result() as $row)
{
$data = array(
'ptitle' =>$row->ptitle,
'technology' => $row->technology,
'description' => $row->description,
);
$this->session->set_userdata('project',$data);
}
here is my View code:
<?php
if (isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
?>
when i print array it displays
Array ( [ptitle] => opmp [technology] => hbh [description] => kg ) Array ( [ptitle] => icicse [technology] => vv [description] => bhjv ) .can someone help me to print this values in view
Setting session should be like this
$data = array(
'ptitle' => $row['ptitle'],
'technology' => $row['technology'],
'description' => $row['description'],
);
$this->session->set_userdata($data);
To retrive them use
if (isset($this->session->userdata['project']))
{
$ptitle = $this->session->userdata('ptitle');
$technology = $this->session->userdata('technology');
$description = $this->session->userdata('description');
}
If your are storing multiple as array in SESSION then you surely need foreach in your view too.
Change from
if(isset($this->session->userdata['project']))
{
$ptitle = ($this->session->userdata['project']['ptitle']);
$technology = ($this->session->userdata['project']['technology']);
$description = ($this->session->userdata['project']['description']);
}
into
if(isset($this->session->userdata['project']))
{
foreach($this->session->userdata['project'] as $project)
{
$ptitle = $project['ptitle'];
$technology = $project['technology'];
$description = $project['description'];
echo $ptitle.'<br>'.$technology.'<br>'.$description.'<br>';
}
}
Try setting your array like bellow and then pass it to session set data.
$project = array("project" =>
array(
'ptitle' => "ptitle",
'technology' => "technology",
'description' => "description",
)
);
$this->session->set_userdata($project);

Multidimensional Array modify values

I'd changed, the data in this line.
$fileConv = $_GET['file']; // It retrieves data to add.
$file = intval($fileConv); // Conversion
$ArrayNotes = array (
0 => array ('titre' => 'aaa','ref' => 'aaa','date' => 'aaa','like' => aaa,'url' => 'aaa'),
1 => array ('titre' => 'aaa1','ref' => 'aaa1','date' => 'aaa1','like' => aaa1,'url' => 'aaa1') // my array
);
$like = $ArrayNotes[$file]['like'] + 1; // The only data that changes.
$donnee = array("titre" => $ArrayNotes[$file]['titre'], "ref" => $ArrayNotes[$file]['ref'],"date" => $ArrayNotes[$file]['date'], "like" => $like, "url" => $ArrayNotes[$file]['url']); // Change Data
As stated, I want to know how to change this data directly.
Example : To add a new line :
array_push($ArrayNotes, $donnee);
$var_str = var_export($ArrayNotes, true);
$var = "<?php\n\n\$ArrayNotes = $var_str;\n\n?>";
file_put_contents('content.php', $var);
Thanks you for your help.
Should be as easy as the following:
$ArrayNotes[$file]['like'] = 1234;
And if you just wish to add one to the existing field, you may do:
$ArrayNotes[$file]['like'] += 1;

building a multi dimentional array from mysqli database query using php

I am trying to build a multi dimentional array of students and their data from my database table using mysqli and php.
I want my array to look something like this
Array #$adult array
(
[626] => Array #student no 626 data
(
[name] => emily,
[age] => 43,
[height] => 156,
)
[627] => #student no 627 data
(
[name] => luke,
[age] => 31,
[height] => 176,
)
)
the number being the members id followed by their data.
So i have tried the following
$sql = "SELECT * FROM pzgym_waitinglist WHERE seen = 0 GROUP BY gym_discipline, school_yr, id";
$result = $db->query($sql);
if ($result->num_rows > 0)
{
#set up array
$adult = array();
while($row = $result->fetch_array())
{
$id = $row["id"];
$name = $row["name"];
$age= $row["age"];
$height = $row['height'];
if($row['gym_discipline'] == "Adult Gymnastics")
{
$adult[$id] = "['name'] => $name, ['age'] => $age, ['height'] => $height";
}
}
}
but this isnt producing the correct results, so im guessing my array building sucks :( here is what i am getting.
Array
(
[626] => ['name'] => Emily, ['age'] => 43, ['height'] => 156
[627] => ['name'] => Luke, ['age'] => 31, ['height'] => 176
)
Could someone help me please to build a successful multi dimentional array from the data im my database
Many Thanks
You need a second level when you create the array, instead of just simply adding keys and data to the array.
So, first create an index (key) with the student ID, then the value of that new index will be a sub-array with all the data for that student.
Then next loop it will do the same for the next student.
Something like:
while($row = $result->fetch_array())
{
$id = $row["id"];
$name = $row["name"];
$age= $row["age"];
$height = $row['height'];
if($row['gym_discipline'] == "Adult Gymnastics")
{
$adult[$id] = array(
"name" => $name,
"age" => $age,
"height" => $height,
);
}
}
Use the array construct:
$adult[$id] = array('name' => $name, 'age' => $age, 'height' => $height);
You need to do in following manner--
$adult[$id]['name'] = $name;
$adult[$id]['age'] = $age;
$adult[$id]['name'] = $height;
Note:- if condition is not required because your array is created through id.

PHP: Display data from Array

I working on a program and coming up with some annoying issue. I am trying to display data from an array. I copied the format from another array I setup and it works perfect. The only difference is I am gathering a lot more data...
Calling the function:
$data1 = display_orders($_SESSION['user_id'], $limit, 'fName', 'lName', 'VendorName', 'DateRequested', 'Shipping', 'VendorNumber', 'VendorFax', 'VendorAddress', 'VendorCity', 'VendorState', 'VendorZip', 'EquipmentConsumable', 'GasType', 'GasLocation', 'UNMTag', 'EquipmentLocation', 'index', 'totalcost', 'Approved', 'Shipped');
The Function itself
<?php
function display_orders($user_id, $limit)
{
$data = array();
$user_id = (int)$user_id;
$limit = (int)$limit;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
// print_r($func_get_args);
if ($func_num_args > 1)
{
unset($func_get_args[0]);
unset($func_get_args[1]);
$fields = '`' . implode('`, `', $func_get_args) . '`';
for($x = 0; $x < $limit; $x++)
{
$data[] = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` , `vendor` WHERE $user_id = users.id AND $user_id = vendor.user_id ORDER BY vendor.DateRequested DESC"));
}
return $data;
}
}
?>
So now i try to echo the data out:
echo $data1['VendorName'];
I get no output.
If I do the following:
print_r ($data1);
I get output!
Array ( [0] => Array ( [fName] => admin [lName] => test [VendorName] => Newegg [DateRequested] => 2013-09-19 [Shipping] => Standard [VendorNumber] => NA [VendorFax] => NA [VendorAddress] => NA [VendorCity] => NA [VendorState] => NA [VendorZip] => 00000 [EquipmentConsumable] => Equipment [GasType] => [GasLocation] => [UNMTag] => 0 [EquipmentLocation] => Computer Lab [index] => 0 [totalcost] => 39.99 [Approved] => 0 [Shipped] => 0 ) )
But if i try to add a field name No data....
Any help and I would be grateful!
As you see, $data1 is Array([0] => Array(...)), so you'll need to call
echo $data1[0]['VendorName'];
This is because you are assigning data as $data[] = mysql_fetch_assoc(...).
echo $data1[0]['VendorName'];
I suggest when using print_r you first echo <PRE> as it will help you to see the true structure of the array easier. In this case, the location of VendorName is one layer deeper than you are echoing.
You forgot the index [0]:
echo $data1[0]['VendorName'];

Categories