Jump to content

[SOLVED] Session Variables in loop


dfowler

Recommended Posts

Hey guys, I'm pulling a bunch of information from a database in a loop.  As I pull the information I want to store them in a $_SESSION variable.  Here is my code so far:

 

$query  = "SELECT * FROM table where id='$k'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
     $_SESSION['item_name'] = $row['name'];
}

 

The problem is that it is only saving the last item.  I'm not sure how to do this correctly as using session variables are rather new to me.

Link to comment
https://forums.phpfreaks.com/topic/86206-solved-session-variables-in-loop/
Share on other sites

Assuming your only looking for the data related to one member, there may only be one record. No need for a while loop.

 

<?php

 session_start();

 $query  = "SELECT * FROM table where id='$k' LIMIT 1";
 if ($result = mysql_query($query)) {
   if (mysql_num_rows($result)) {
     $row = mysql_fetch_array($result);
     foreach ($row as $k => $v) {
       $_SESSION[$k] = $v;
     }
   }
 }

?>

No, there will be multiple data.  The user will can pick either one or multiple items that they want to look at.  It's going to be a shopping cart system.

 

Screen 1

The user picks what they want to look at

 

Screen 2

shows what they picked on screen #1

 

Screen 3

processes checkout

Then your going to need to append something to the $key on each iteration of your while loop. eg;

 

<?php

  session_start();
  $index = 0;

  $query  = "SELECT * FROM table where id='$k'";
  if ($result = mysql_query($query)) {
    if (mysql_num_rows($result)) {
      while ($row = mysql_fetch_array($result)) {
        foreach ($row as $k => $v) {
          $_SESSION[$k . '_' . $index] = $v;
          $index++;
        }
      }
    }
  }

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.