Store and check multiple $_SESSION - php

I have 3 objects with same variable but rendered with diferent values.
001 - Title one
002 - Title two
003 - Title three
I need to check on another block of page if this first three are the same. The only thing that comes to mind is store this variables in a $_SESSION. So far so good. The problem is that it only stores last value (obviously).
CODE
/* -- block one --*/
session_start();
$_SESSION['lasttitle'] = $item->getTitle;
echo $item->getTitle(); //rendering 1st object
echo $item->getTitle(); //rendering 2nd object
echo $item->getTitle(); //rendering 3rd object
/* -- block two --*/
session_start();
$last3 = $_SESSION['lasttitle'];
if($item->getTitle() != $last3) {
//don't render last 3
}

$_SESSION['lastTitles'][] = $item->getTitle();
$_SESSION['lastTitles'] = array_slice($_SESSION['lastTitles'], -3);
..
if (in_array($item->getTitle(), $_SESSION['lastTitles'])) ..
This stores an array of the last three titles, and checks whether a title is in this array.

Create multidimensional session:
$_SESSION['lasttitle'][$item->id] = $item->getTitle();
$_SESSION['lasttitle'][$item2->id] = $item2->getTitle();
$_SESSION['lasttitle'][$item3->id] = $item3->getTitle();
And check if that element is in array:
$total = 0;
foreach ($items as $item) {
if (isset($_SESSION['lasttitle'][$item->id])) {
$total++;
}
}
if ($total == 3) {
// Do something, it's all 3 titles in session!
}
I know it may be better solution, but I don't understand full algorithm. Also, to compare some arrays, you can use array_diff_assoc()

I think storing data as array in session might help you. Simply gather all titles you need in an array and put it into $_SESSION (instead of one variable). One the next page you will be able to analyze data you have and choose variables you need.

Related

Array index increment

I have this array in php code. I want to have that whenever page is being called it should print value of first array index and when next time second value of array index and so on... what modification I could do? for now it´s printing everything when being called single time.
<html>
<?php
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
foreach ($addresses as &$value) {
echo $value ;
}
?>
</html>
I'm not sure if I understood what you want. But if you want to print the first array's value when the page loads one time, the second array's value when the page loads another time and so on, you can do this:
<?php
if(!isset($addresses) || empty($addresses)){ //checks if the array is not initialized or if it's empty
$addresses = array('ifcbxespra', 'ifcheqjbmea', 'ifcqiknsa', 'ifcqirtjla', 'ifcwqsrlmn', 'ifclmkmzhz','ifcwdujhgc','ifcihddngh','icffhzudcd','ifchnsqzgs','ifcgssqrhg');
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}else{
echo $addresses[0]; //print the first value
array_splice($addresses, 0, 1); //removes the first element of the array and reindexes it
}
The logic behinds it is: if the array already exists and is not empty (it has values), print the first value and then remove it, so next time the first value will be the second actual value. When the array is empty, redefine it as to start again.
You can search for more information on array_splice() here.
P.S.: you have to use PHP's $_SESSION to save the array between the pages.
You can use something like $_SESSION and store there the last index.
For example:
$array = array('one', 'two', 'three');
if (!$_SESSION['nextIndex'] || $_SESSION['nextIndex'] >= count($array)) {
$_SESSION['nextIndex'] = 0
}
// print the value
echo $array[$_SESSION['nextIndex']];
// increment the nextIndex
$_SESSION['nextIndex']++;
NOTE: This will only work for the same user. Each page reload will increment the array index. But if you need some cross-user counting, then you have to store the information somewhere on the server, like a DB or even a simple txt file.
Check out this example: http://hibbard.eu/how-to-make-a-simple-visitor-counter-using-php/
Finally I solved this problem with the MySQL. created a column with all code. and then call the script every-time when user press button. In the script first I fetch first raw and print that value, and then, delete that raw. so every-time user will get unique value from the list of code And it is working fine.

fetch data from model that is called in loop

I have a controller function in CodeIgniter that looks like this:
$perm = $this->job_m->getIdByGroup();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
What I need to do is list the data in the result in the view, but I get only the last value while using this method. How can I pass all the results to the view?
Store it in an array. Like this:
foreach($perm as $pe=>$p){
$result[] = $this->job_m->getDatapermission($p['id']);
}
Because $result is not an array...
try this:
$result=array();
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[] = $this->job_m->getDatapermission($pId);
}
$data['permission'] = $result;
Note:
My answer uses a counter to enable the display of a single group result when needed.
Guessing from your need to loop and display the value of $result, possibly, it is an array or object returned by $query->result(). Things could be a bit complex.
Example: if $perm is an array of 5 items( or groups), the counter assigns keys 1 - 5 instead of 0 - 4 as would [] which could be misleading. Using the first view example, you could choose to display a single group value if you wants by passing it via a url segment. Making the code more flexible and reusable. E.g. You want to show just returns for group 2, in my example, $result[2] would do just that else next code runs. See my comments in the code.
$perm = $this->job_m->getIdByGroup();
$counter = 1;
foreach($perm as $pe=>$p)
{
$pId = $p['id'];
$result[$counter] = $this->job_m->getDatapermission($pId);
$counter++;
}
$data['permission'] = $result;
As mentioned above Note:
I Added a Counter or Key so you target specific level. If the groups are:
Men, Women, Boys, Girls, Children; you'd know women is group two(2) If you desire to display values for just that group, you don't need to rewrite the code below. Just pass the group key would be as easy as telling it by their sequence. To display all the loop without restrictions, use the second view example. To use both, use an if statement for that.
###To access it you could target a specific level like
if(isset($permission)){
foreach($permission[2] as $key => $value){
echo $value->columnname;
}
###To get all results:
foreach($permission as $array){
foreach($array as $key => $value){
echo $value->columnname;
}
}
}

PHP - associative array - blank row being added

I am trying to build Dynamic UI by getting data from DB using CodeIgniter but facing problem in constructing array.
Requirement:
Get parent menu items in an array. Then get child item corresponding to each parent item.
Code to get data for parent element::
$data['menu'] = $this->Menu->get_admin_menu_data();
This gives me 3 records
echo "before loop menu" . count($data['menu']) . "</br>"; //prints 3
Now I run a foreach loop for each parent item to retrieve it's child item
foreach($data['menu'] as $menu){
$data['menu']['menu_item'] = $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
echo "inside loop menu " . count($data['menu']) . "</br>"; //prints 4
}
As soon as I do this the count of menu increases to 4 resulting in error in UI.
I am new to PHP so now sure what is the best way to create a structure to hold this type of data.
Please help!!!!
If $data['menu'] contains 3 key/value pairs, but $data['menu']['menu_item'] is not set, your statement
$data['menu']['menu_item']
= $this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
sets just this.
Thus count( $data['menu'] ) returns 4 elements afterwards - including the newly added 'menu_item' key.
I don't know CodeIgniter, but overwriting a static variable
$data['menu']['menu_item'] = "someting"
never makes sense. Where do you really want to store the result of
$this->Menu->get_admin_menu_item_data($menu->ad_menu_id);
? You can and should check the content of a variable using var_dump.

How to add visited pages urls into a session array?

Everytime the user visit a page, the page url will be stored into an array session. I want to have 10 elements in the array only. So that 10 elements will save 10 latest visited page urls. Here is my codes :
<?php
$currentpageurl = $_GET['username'];
$urlarray=array();
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
foreach($_SESSION['pageurl'] as $key=>$value)
{
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>
I tested the code, it always overwrite the element in the array with new visited page, thus it has only 1 element in the array. How to make it not to overwrite the element?
You are always overwriting the array with a new one here:
$urlarray=array(); // new empty array
$urlarray[] = $currentpageurl;
$_SESSION['pageurl']=$urlarray;
Instead use:
session_start();
// like #Kwpolska said, you probably miss that, so $_SESSION didnt work
is_array($_SESSION["pageurl"]) or $_SESSION["pageurl"] = array();
// fix for your current problem
$_SESSION['pageurl'][] = $currentpageurl;
// This appends it right onto an array.
$_SESSION["pageurl"] = array_slice($_SESSION["pageurl"], -10);
// to cut it down to the last 10 elements
Simplest way to do this and keep just the last 10 entries will be to create your initial array with the correct size (via array_fill()). Then we can push new items onto the beginning of the array and pop old items off the other end using array_unshift() and array_pop().
session_start();
// Initialise URL array with 10 entries.
if (empty($_SESSION['pageurls'])) {
$_SESSION['pageurls'] = array_fill(0,10,'');
}
function trackPage($url) {
array_unshift($_SESSION['pageurls'],$url);
array_pop($_SESSION['pageurls']);
}
Make sure the above code always runs first. Then you can pass new URLs to the array when you want. So, perhaps something like:
trackPage($_SERVER['REQUEST_URI']);
You've ommitted session_start();. Working code (without trimming):
<?php
session_start();
$currentpageurl = $_GET['username'];
$_SESSION['pageurl'][] = $currentpageurl;
foreach($_SESSION['pageurl'] as $key=>$value) {
echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' <br />';
}
?>

Foreach value from POST from form

I post some data over to another page from a form. It's a shopping cart, and the form that's being submitted is being generated on the page before depending on how many items are in the cart. For example, if there's only 1 items then we only have the field name 'item_name_1' which should store a value like "Sticker" and 'item_price_1' which stores the price of that item. But if someone has 5 items, we would need 'item_name_2', 'item_name_3', etc. to get the values for each item up to the fifth one.
What would be the best way to loop through those items to get the values?
Here's what I have, which obviously isn't working.
extract($_POST);
$x = 1; // Assuming there's always one item we're on this page, we set the variable to get into the loop
while(${'item_name_' .$x} != '') {
echo ${'item_name' .$x};
$x++;
}
I'm still relatively new to this kind of usage, so I'm not entirely how the best way to deal with it.
Thanks.
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
Use array-like fields:
<input name="name_for_the_items[]"/>
You can loop through the fields:
foreach($_POST['name_for_the_items'] as $item)
{
//do something with $item
}
If your post keys have to be parsed and the keys are sequences with data, you can try this:
Post data example: Storeitem|14=data14
foreach($_POST as $key => $value){
$key=Filterdata($key); $value=Filterdata($value);
echo($key."=".$value."<br>");
}
then you can use strpos to isolate the end of the key separating the number from the key.
i wouldn't do it this way
I'd use name arrays in the form elements
so i'd get the layout
$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';
then you could do an array slice to get the amount you need

Categories