Jump to content

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++;
        }
      }
    }
  }

?>

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.