Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

How to get my sessions to work with key/value/pairs ?

Posted on 2011-04-28
26
Medium Priority
?
294 Views
Last Modified: 2012-05-11
Hi, I am trying to store and retrieve the quantity that was selected for a clicked product:

function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		if(!isset($_SESSION['items'])) {
			$_SESSION['items'] = array();
		}
		$_SESSION['items'] = array(
			$item => $qty
		);
		array_push($_SESSION['items'], $item, $qty);
		$quantity = $_SESSION['items'];
		$qty = $quantity[$item];
		return $qty;
	}
}

Open in new window


It works and displays the quantity in my shopping cart right after I clicked the product and it re-directs me, but if I come back to view the shopping cart the quantity is missing.  Anyone know why its not storing it in a session?
0
Comment
Question by:FairyBusiness
  • 13
  • 13
26 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488489
What is "mysql_clean_strings" and can you tell if you are saving anything in your sessions?
0
 

Author Comment

by:FairyBusiness
ID: 35488497
mysql_clean_strings is a function that I wrote, it always works fine.

I am saving things in other sessions.  But the sessions here in this function aren't doing the job.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488521
You said above that the routine you posted is working.  What isn't working?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:FairyBusiness
ID: 35488536
The shopping cart only displays the quantity if I just immediately came from selecting a product.  If I come back to the shopping cart the quantity is gone.  So what isn't working is the sessions.

Also, when I say it "works" I mean I'm not getting any errors and its kind of doing what I want.  When it does display a quantity right after clicking a product it puts that quantity in the quantity for all of the products in the shopping cart.  So its the same quantity everywhere until I leave that page then its black again.
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488625
Write up a simple PHP page that takes a list of items with quantities and puts them in your session variables the way you think it should work and at the end, do a 'print_r' of the session variable where they are stored to see if they're being entered as you think they are.  Since you've been working on this for a while, I'm going to assume that you have 'session_start()' at the top of Every page.  ??
0
 

Author Comment

by:FairyBusiness
ID: 35488665
one thing that would help me alot first is:

how do I return an array?

function cart();
$bag = get_item();
      if(!isset($_SESSION['cart'])) {
            $_SESSION['cart'] = array();
      }
      array_push($_SESSION['cart'], $bag);
      $cart = $_SESSION['cart'];
return $cart;
}

The problem is its only returning the first thing in the array, but I need to return this in different places.
0
 
LVL 84

Accepted Solution

by:
Dave Baldwin earned 2000 total points
ID: 35488673
Here's a simple demo.
<?php 
error_reporting(E_ALL);
ini_set('display_errors','On');
session_start(); 
$_SESSION['items'] = array();
$_SESSION['items']["base"] = 0;
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
 "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<title>Session Array Variable test</title>
</head>
<body>
<h1>Session Array Variable test</h1>
<?php 

function setss($item, $qty) {
	//$_SESSION['items'][] = array($item, $qty);
	$_SESSION['items'][$item] = $qty;
	}

setss("shirt",2);
setss("plate",1);
setss("fork",3);

print_r($_SESSION['items']);
echo "<br><br>";
echo '<table border="1" cellpadding="3" cellspacing="0" summary="">';
$cart = $_SESSION['items'];
foreach($cart as $it => $qt){
	echo "<tr><td><b>Item:</b></td><td>&nbsp;$it&nbsp;</td><td><b>Qty:</b></td><td>&nbsp;$qt&nbsp;</td></tr>";
	}
echo "</table>";
 ?>

</body>
</html>

Open in new window

0
 

Author Comment

by:FairyBusiness
ID: 35488688
Thanks this will help a lot!  

But tell me, why do you have these outside of the function?

$_SESSION['items'] = array();
$_SESSION['items']["base"] = 0;


and what is the base for? do we ever use that?
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488709
I used them to initialize the $_SESSION['items'] variable correctly.  'base' is just the name of the first item (and the 'key') and 0 is the quantity.  You should probably have something similar in your code where the cart is first created.
0
 

Author Comment

by:FairyBusiness
ID: 35488771
Ok, I feel stuck again.  I tried to combine some of your code with mine (because I have to build a  whole shopping cart)

function cart() {
	$bag = get_item();
	if(!isset($_SESSION['cart'])) {
		$_SESSION['cart'] = array();
	}
	array_push($_SESSION['cart'], $bag);
	$cart =& $_SESSION['cart'];
}
function cart_details($item, $table, $column) {
    global $conn, $table;
    $query = "SELECT " . $column . " FROM " . $table . " WHERE filename='" . $item. "'";
    $result = mysql_query($query, $conn);
    confirm_query($result);
    while ($row = mysql_fetch_array($result)){
				$data = $row[$column];
    }
	return $data;
}
function build_cart() {
	$cart = cart();
	foreach($cart as $item => $qty) {   // LINE 272
		switch($item[0]) { // matches the first letter to a table
		  case 'b':
				$table = 'bracelets';
				$output =  "<tr>";
				$output .= "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'n':
				$table = 'necklaces';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'e':
				$table = 'earrings';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  }
		return $output;
	}
}

Open in new window


But I got this message:  ( I commented which line it is)

Warning: Invalid argument supplied for foreach() in /hermes/web09c/b2950/moo.auroriellacom/includes/library.php on line 272

Is my cart function not valid?
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488797
"$cart =& $_SESSION['cart'];"  Why is the '&' in there?  I can't find any such operator.  That alone makes $cart invalid.

And you haven't said what your structure is supposed to look like.  

And using '$cart' and 'cart()' is too confusing for me.  I would use at least a slightly different spelling for each one like '$cartdat' and 'cartfunc()'.
0
 

Author Comment

by:FairyBusiness
ID: 35488835
ok I changed it:  (it was starting to confuse me too lol)

function cart() {
	if(!isset($_SESSION['cart'])) {
		$_SESSION['cart'] = array();
	}
}
function get_qty($item) {
	if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
		$qty = trim(mysql_clean_strings($_POST['qty']));
		$_SESSION['cart'][$item] = $qty;
	}
}
function cart_details($item, $table, $column) {
    global $conn, $table;
    $query = "SELECT " . $column . " FROM " . $table . " WHERE filename='" . $item. "'";
	var_dump($query);
    $result = mysql_query($query, $conn);
    confirm_query($result);
    while ($row = mysql_fetch_array($result)){
				$data = $row[$column];
    }
	return $data;
}
function build_cart() {
	$cart = $_SESSION['cart'];
	foreach($cart as $item => $qty) {
		switch($item[0]) { // matches the first letter to a table
		  case 'b':
				$table = 'bracelets';
				$output =  "<tr>";
				$output .= "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'n':
				$table = 'necklaces';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'e':
				$table = 'earrings';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  }
		return $output;
	}
}

Open in new window


Its not storing anything from any of these functions in session because I did a print_r($_SESSION) and got only my login sessions back:

Array ( [user_id] => 1 [username] => AdminTanya [cart] => Array ( ) )


This is my website:  (its a bit of mess right now)  b3 or b4 are the item numbers I am testing so adding other products to the shopping cart won't work.

http://www.auroriella.com/bracelet.php?item=b3
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488860
Yes, I've seen that before.  You need to resize those images before displaying them they are taking way too long to load.  You're sending 4 times as much data as needed.

And I'll say this for the third time:  What is the structure of your 'cart'?  You have to have a plan in order to write the code.  The demo I posted is pretty clear about what is supposed to happen in it.
0
 

Author Comment

by:FairyBusiness
ID: 35488874
Its a pretty simple structure I think.  One that simply displays the selected product, its price, quantity, and later I'll add a remove and update button.

With your demo you manually set the items and its quantity so thats why its more simple then mine.  I have to grab the qty from the quantity selection input and the item name from the url (e.i. b3) and then have them match up again in the shopping cart.

(I'll resize the images later)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488896
In my code, each item is listed at $_SESSION['items'][$item] = $qty; so I know where to find them.  That is what I am talking about.  You have to know this about your setup to get it right.  I don't see clearly in your code where you think things are located.
0
 

Author Comment

by:FairyBusiness
ID: 35488899
ok I tried to duplicate that in my get quantity function:

$_SESSION['cart'][$item] = $qty;

function get_qty($item) {
      if(isset($_POST['submit']) && empty($errors)) { // Form has been submitted
            $qty = trim(mysql_clean_strings($_POST['qty']));
            $_SESSION['cart'][$item] = $qty;
      }
}
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488916
Where is '$item' coming from?  If '$item' is blank, you're assigning '$qty' to a blank 'key'.  Maybe repeatedly.
0
 

Author Comment

by:FairyBusiness
ID: 35488922
on my page I have: (bracelet.php)

cart();
$item = get_item();
get_qty($item)

This is in my library:

function get_item() {
      if(isset($_GET['item'])) {
            $item = $_GET['item'];
            return $item;
      }
      elseif(isset($_GET['bag'])) {
            $bag = $_GET['bag'];
            return $bag;
      }
}
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35488948
Do yo have anything in your database yet?
0
 

Author Comment

by:FairyBusiness
ID: 35488961
Yes, I have many things in the database.  But I am only testing

http://www.auroriella.com/bracelet.php?item=b4 

and

http://www.auroriella.com/bracelet.php?item=b3

because they have enough information in the database for this.

(The title above the image is the name, and the price is to the side. Those are the only things I am pulling from the database for this and they are already on the page)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35489010
Well, you're not pulling them from the database yet.  At least not to the screen.  And you're querying the database 3 times for every item.  The query should be done once for each item.  '$rows' is an array that you can return and use in creating your table.
0
 

Author Comment

by:FairyBusiness
ID: 35489045
ok well its working better now!

http://www.auroriella.com/bracelet.php?item=b4 

only problem is if I then click on the product here:


http://www.auroriella.com/bracelet.php?item=b3

it still displays the one from the first click.  but at least its finally doing something!!
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35489073
Array 2 has both items.  If that's the one you're using, then your 'foreach' isn't working yet.
0
 

Author Comment

by:FairyBusiness
ID: 35489099
OK I believe everything is working except for my foreach loop

http://www.auroriella.com/show_cart.php

Do I have the return $output in the wrong place?  Because it always just goes through it once. . . and then stops

function build_cart() {
	$cart = $_SESSION['cart'];
	foreach($cart as $item => $qty) {
		switch($item[0]) { // matches the first letter to a table
		  case 'b':
				$table = 'bracelets';
				$output =  "<tr>";
				$output .= "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'n':
				$table = 'necklaces';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  case 'e':
				$table = 'earrings';
				$output =  "<tr>";
				$output .=  "<td>" . cart_details($item, $table, $column='name') . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "<td>" . $qty . "</td>";
				$output .=  "<td>" . cart_details($item, $table, $column='price') . "</td>";
				$output .=  "</tr>";
				break;
		  }
	}
	return $output;
}

Open in new window

0
 

Author Comment

by:FairyBusiness
ID: 35489138
finally it works!!!!!!!!!!!!!!!

:))

It was going thru the foreach loop every time the problem was the $output

bc the first one only has  =  and all the rest have  .=

so when it goes back thru again its stop by the = not having a period!!

Thanks for all of your help tonight :)
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 35489206
You're welcome.  Thanks for the points.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This holiday season, we’re giving away the gift of knowledge—tech knowledge, that is. Keep reading to see what hacks, tips, and trends we have wrapped and waiting for you under the tree.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question