This question already has answers here:
PHP foreach overwrite all items with last item
(5 answers)
Closed last year.
Please see the test page here https://wintoweb.com/sandbox/question_3.php
I use $_SESSION to store results of DB searches but only the last value is stored in the session. Looks like the latter is emptied upon each search.
I've used session before on that server and had no problems. My code is probably faulty but I cannot figure it out. session_start is called at top of file.
<?php
if(isset($_GET['search'])){
} else if(isset($_GET['display_this'])){
$rets = getNames(); //The $rets will hold the value returned by your function getName().
if(!empty($rets)){
echo '</br><b>Your selections so far :</b></br></br>';
}
//But yet, only the last search is stored in the session (why?)
echo "Echo of session array : " . $_SESSION['author'] . "<br>";
}
function getNames(){
$rets = '';
if(isset($_GET['choices']) and !empty($_GET['choices'])){
foreach($_GET['choices'] as $selected){
$rets .= $selected . ' -- ';
// This should add every $rets to the session array. Right?
$_SESSION['author'] = $rets;
//session_write_close();
}
}
return $rets;
}
?>
I expect the session to retain all info from subsequent searches but only the last value is stored.
A couple of things. I'll explain within the code.
// make sure that the function is before it is called.
// computers execute code top to bottom, and so getNames wouldn't even exist yet
// so therefore your if statement (below) will always evaluate to false
function getNames($choices){
// use parameters instead of $_GET inside of a function
$rets = '';
if(isset($choices) && !empty($choices)){
foreach($choices as $selected){
$rets .= $selected . ' -- ';
// you need to append using '.=' not '=' otherwise all the data will be overwritten
$_SESSION["author"] .= $rets;
}
}
return $rets;
}
// you shouldn't be checking if something isset and then doing nothing about it
// you might as well just be checking if it isn't.
if(!isset($_GET["search"]) && isset($_GET['display_this'])){
$rets = getNames($_GET["choices"]);
if(!empty($rets)){
echo '</br><b>Your selections so far :</b></br></br>';
}
echo "Echo of session array : " . $_SESSION['author'] . "<br>";
}
// you need to move this to the end of your script, otherwise the session will be closed
// before the second iteration of your loop begins and you won't be able to change values
// or access them later on (like in the above if statement)
session_write_close();
You are overwriting your Session array everytime with new value. You need to append to it, just like you are appending to $rets variable.
$_SESSION['author'] .= $rets;
Related
I am trying to add new items to my array if they don't already exist but below code shows me an error:
// Check if session exists
if(!isset($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
$_SESSION['coupon']['couponcode'][] = $coupon;
}
$_SESSION['coupon']['couponcode'][] = $coupon;
Gives: PHP Fatal error: Uncaught Error: [] operator not supported for strings
But I thought this was the way to add to the array, if I remove the brackets it just replaces the value everytime.
I have session_start(); everywhere at the top of my pages.
You can use array_push():
if(empty($_SESSION['coupon'])){
// Create array from session
$_SESSION['coupon']['couponcode'] = array();
}
else
{
if(!in_array( $coupon,$_SESSION['coupon']['couponcode'])) //check in array available
{
array_push($_SESSION['coupon']['couponcode'], $coupon); //push to array
}
}
First of all,do not put blindly session_start() on top of every page. It will start session again even if a previous session was running and will refresh your all values, so first thing, change that to:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
this way it starts the session only if it doesn't exist.
Now, you are getting error because somehow your $_SESSION['coupon']['couponcode'] is a string so add an additional check:
if(!isset($_SESSION['coupon']['couponcode'][$coupon])){
// Add couponcode to session if it does not already exist
if (empty($_SESSION['coupon']['couponcode']) || !is_array($_SESSION['coupon']['couponcode']))) {
$_SESSION['coupon']['couponcode'] = [];
}
$_SESSION['coupon']['couponcode'][] = $coupon;
}
I'm designing a semi-basic tool in php, I have more experience server side, and not in php.
My tool contains 10-15 pages, and I am doing the navigation between them with the $_GET parameter.
I would like to check if the query string is empty (to know if I'm in the home page). Is there any php function for this ? Of course I can do it manually, but still?
EDIT: My question is if there is a function that replaces
if(! isset("param1") && .....&& ! isset("paramN")){
...
}
Try below
if(isset($_GET['YOUR_VARIABLE_NAME']) && !empty($_GET['YOUR_VARIABLE_NAME'])) {
}
isset() is used to check whether there is any such variable or not
empty() to check whether the variable is not empty or not
As per your comment, assume your URL as below
http://192.168.100.68/stack/php/get.php?id=&name=&action=delete&type=category
And your PHP script as below
<?php
$qs = $_GET;
$result = '';
foreach($qs as $key=>$val){
if(empty($val)){
$result .= 'Query String \''.$key.'\' is empty. <br />';
}
}
echo '<pre>'; print_r($result);
?>
In my above URL I passed id and name as empty.
Hence, Result will be like below
id is empty.
name is empty.
but I dont think its standard way.
If you want to process something only if all parameters are having some values, they you can move those process inside a if as below
if(empty($result)) {
// YOUR PROCESS CODE GOES HERE
} else {
echo 'Some Required Parameters are missing. Check again';
}
I switched my code to PDO and I almost there, except for this part where all results from a query are supposed to be displayed with a foreach statement. I know the data is being fetched properly and is correctly stored in $row2.
What I need to do is get take the 'position' variable from $results2 and add 1 to it and then run the foreach loops where position is equal to that new number...
BEFORE I SWITCHED TO PDO, my code was working perfectly and this did correctly display the 2 expected results:
$cont = $results2[0]->position;;
$cont++;
foreach ($results2 as $resulting) {
if ( $results2[0]->position = $cont )
{
echo "<hr><br><br>" . $resulting->text . " " . " <b>Suggested by: $resulting-
>display_name </b><br>|<b> Approve this contribution</b> | <b>delete this suggestion</b> |";
}
}
But now, the foreach only returns the same first result twice after the conversion to PDO, which looks like this:
//NEW PDO CODE--DOESN'T DISPLAY BOTH RESULTS:
$results2->execute();
$row2 = $results2->fetchAll(PDO::FETCH_ASSOC);
$cont = $row2[0]['position'];
$cont++;
foreach ($row2 as $resulting) {
if ( $row2[0]['position'] == $cont )
{
echo "<hr><br><br>" . $row2[0][text] . " " . " <b>Suggested by:" . $row2[0]
[display_name] . "</b><br>|<b> Approve this contribution</b> | <b>
delete this suggestion</b> |";
}
}
It looks like your old code was fetching an array of objects, whereas your new code is fetching an array of arrays (indicated by PDO::FETCH_ASSOC).
So while $results2[0]->position used to work, you mistakenly replaced it with $row2[0][position]. However, position needs to be quoted in the second case since it is an array index.
If you had all of your error reporting turned on, you would have easily seen this.
The same applies to $row2[0][text] and $row2[0][display_name]. In addition to the lack of quotes on these indexes, you probably really want $resulting instead of $row[0] since $row[0] will give you the same values each time through the loop. So those should probably be changed to $resulting['text'] and $resulting['display_name']
So replace all instances of $row2[0][position] with $row2[0]['position']. Also, heed the advice of John Ruddell.
NOTE: this is not an answer... its just a way for me to clarify what I was saying in comments because its hard to show code in comments.
GENERAL IF CODE LOGIC:
if (true){
// code will always execute on true
}
if (false){
// code will never execute on false
}
sample:
$key = "12345";
if($key){
// will always be executed because this is a true statement.
}
your code:
if ( $row2[0]['position'] = $cont ){
// will always execute because the assignment is true
}
NOW:
with all that aside.. if nothing is happening when you run it with == that means that the count is not equal to the $row[0][position] so its a false statement and the code inside the if does not get executed.
RECOMMENDATION:
try putting an echo $cont; and echo $row2[0]['position']; before the if statement to see whats going on.
At the moment i'm calling the following via GET
$RimWidth = $_GET['RimWidth'];
$TyreWidth = $_GET['TyreWidth'];
$Aspect = $_GET['Aspect'];
$TyreDia = $_GET['TyreDia'];
$TyreMan = $_GET['TyreMan'];
However in my paginiation, after page 1 it looses the variables and doesn't work. I understand i need to store them in the session. How do i do this as i've seen a few way of doing it and can't get it to work and how do i place them onto the end of the pagination links which look like this
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
thanks
If you want to just repeat the $_GET values, you can make a function to do that:
//A function to get and repeat arguments in every link
function repeatvars(){
if(isset($_GET) && empty($_GET) == false){
$variables = "?";
$arraycount = count($_GET) - 1;
$count = 0;
foreach ($_GET as $var => $value){
if(empty($value) == true){
$variables .= $var;
}else{
$variables .= $var."=".$value;
}
if ($count !== $arraycount){
$variables .= "&";
}
$count++;
}
return $variables;
}}
//Example
echo 'Next Page (Link: nextpage.php'.repeatvars().')';
You need this at the top of your PHP pages if using sessions:
session_start();
Then, you should really do this for each one:
$RimWidth = isset($_GET['RimWidth']) ? trim(strip_tags($_GET['RimWidth'])) : null;
$_SESSION['RimWidth'] = $RimWidth;
// and so on
trim() and strip_tags() removes any unwanted white-space and removes any malicious script tags being sent to your page. Never trust any POST, GET or SESSION data. They can all be compromised by hackers. If RimWidth always returns an integer, then put (int) before, like this:
(int) $RimWidth = isset($_GET['RimWidth']).............
You shouldn't need to add the session variables to the end of your pagination links, they're session variables and will be available on the next page, or any other page.
To call them on another page, do this:
echo $_SESSION['RimWidth'];
I am just trying to write a function in php that adds to the discount array but it doesn't seem to work at all.
function addToDiscountArray($item){
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Every time I refresh the page it acts like $_SESSION["discountCalculator"] hasn't been set up but I can't understand why. Whilst writing can I use the $_SESSION["discountCalculator"] in a foreach php loop in the normal way too?
Many thanks
The fact that every time $_SESSION['discountCalculator'] seems not to be set, could be because $_SESSION is not set (NULL). This case happens mostly when you did not executed session_start() at the beginning of you page.
Try adding session_start() at the beginning of the function.
function addToDiscountArray($item) {
if (!$_SESSION) { // $_SESSION is NULL if session is not started
session_start(); // we need to start the session to populate it
}
// if we already have the discount array set up
if(isset($_SESSION["discountCalculator"])){
// check that this item is not already in the array
if(!(in_array($item,$_SESSION["discountCalculator"]))){
// add it to the array if it isn't already present
array_push($_SESSION["discountCalculator"], $item);
}
}
else{
$array = array($item);
// if the array hasn't been set up, initialise it and add $item
$_SESSION["discountCalculator"] = $array;
}
}
Notice that this will not affect the function if the session is already started. It will only run ´session_start()` if the session is not started.