We help IT Professionals succeed at work.

Why is my foreach loop not returning values from $_SESSION variable

peter-cooper
peter-cooper asked
on
556 Views
Last Modified: 2017-04-15
Hi
I have set a $_SESSION variable and cannot see why my foreach loop is not working. All get if I echo the var $v all I get is white screen. If I echo my session var then I can see the data that is being passed is in the format wd10,wd11,wd12.  I would be grateful if someone could check my loop and point out my mistake. Thanks

session var

$_SESSION['boxdest2']

Open in new window


Loop

<?php

foreach ($_SESSION['boxdest2'] as $key=>$value)
	{	
  $temp = explode(",", $value);
  foreach($temp as $k => $v )
  {
    $query = "SELECT * FROM boxes WHERE customer = '$_SESSION[kt_idcode_usr]' AND status = 1 AND custref = '$v'";
    $result = mysql_query($query) or die(mysql_error());
    $row = mysql_fetch_array($result) or die(mysql_error());
    $rack = $row['rack'] . "-" . $row['column'] . "-" . $row['row'] .  "-" . "(" . $row['bay'] . ")";
		
//    $query = "UPDATE boxes SET status = '9' WHERE customer = '$customer' AND department = '$dept' AND custref = '$v'";
//    mysql_query($query) or die('Error, query failed');
//	
	$query = 'INSERT INTO `act` (`slot`, `service`, `activity`, `department`, `company`, `address`, `user`, `item`, `destroyedby`, `destroyedby_date`, `date`, `new`) VALUES (\''.$rack.'\', \''.$service.'\', \''.$activitys.'\', \''.$dept.'\', \''.$company.'\', \''.$address.'\', \''.$user.'\', \''.$v.'\', \''.$user.'\',NOW(),NOW(), \''.$new.'\');';
   mysql_query($query) or die('Error, query failed');
	}
	}
?>

Open in new window

Comment
Watch Question

Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
The first thing is that session_start(); needs to be at the top of your script so your code can find the SESSION.

http://php.net/manual/en/function.session-start.php
Most Valuable Expert 2011
Author of the Year 2014

Commented:
white screen
This is usually a symptom of an error occurring in a script that has error reporting disabled.  Suggest you add error_reporting(E_ALL) to the top of all your PHP scripts and fix the things that cause error, warning and notice messages.  Here is how the session works.  Use session_start() before you access any of the contents of $_SESSION.
https://www.experts-exchange.com/articles/11909/PHP-Sessions-Simpler-Than-You-May-Think.html

Also recommend you treat the MySQL issue as urgent.  Please see the note here.  It's not hard to fix, especially if you use object-oriented MySQLi.  If you don't fix it, your scripts will  begin to fail at run time (perhaps with the white screen of death) and the only thing you won't know is when the failures will being to occur.  I wouldn't want that kind of uncertainty hanging over my head!
https://www.experts-exchange.com/articles/11177/PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

If you're ever in doubt about what information might be in a PHP variable, you can use var_dump() to visualize the information.   Example: var_dump($_SESSION);

A couple of other things you might want to take a look at...

Don't use fetch_array() functions unless you know exactly why you need them.  Instead choose fetch_object().  It is much  more efficient.  Details here: https://www.experts-exchange.com/articles/12293/AntiPHPatterns-and-AntiPHPractices.html. In the article, look for 27. Overlooking Meaningful Optimization

Avoid the use of die() when what you really want is trigger_error() instead.
https://www.experts-exchange.com/articles/29115/PHP-Error-Handling-Never-Say-die-Again.html

Consider this statement:
$row = mysql_fetch_array($result) or die(mysql_error());

Open in new window

That's the wrong way to deal with an empty results set.  If your script gets to that line of code, the query was successful!  So there is no reasonable expectation that the script should die, nor that mysql_error() would have a meaningful value.  If $row is empty, it's because the query did not find anything that matched the WHERE clause.  This is a perfectly normal and expected behavior for MySQL databases, and certainly not a reason to terminate the script.

Author

Commented:
Thanks for comments. However, in my post I state the comment below. So yes, session_start() is at the top of the page.

If I echo my session var then I can see the data that is being passed is in the format wd10,wd11,wd12
Most Valuable Expert 2011
Author of the Year 2014

Commented:
OK, but we did not see session_start() in the code snippet, and omitting it is a common mistake.  So please let us see the data.  Please use var_dump($_SESSION) and post the output in the code snippet here.  This should be enough to get the information we need to see.  Please use your browser's view source feature and copy the information from that view, thanks.
<?php
error_reporting(E_ALL);
session_start();
var_dump($_SESSION);

Open in new window

Author

Commented:
Here you go ray:

'boxdest2' => string 'WD10,WD11,WD12' (length=14)

Open in new window

Most Valuable Expert 2011
Author of the Year 2014
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks very much Ray. Exactly what I wanted to see which enabled me to code this correctly. Many thanks
Most Valuable Expert 2011
Author of the Year 2014

Commented:
Glad to help, and best of luck with your project, ~Ray

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.