We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

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

FairyBusiness
on
Medium Priority
309 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?
Comment
Watch Question

Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
What is "mysql_clean_strings" and can you tell if you are saving anything in your sessions?

Author

Commented:
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.
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
You said above that the routine you posted is working.  What isn't working?

Author

Commented:
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.
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.  ??

Author

Commented:
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.
Fixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
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?
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

Commented:
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?
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
"$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()'.

Author

Commented:
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
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

Commented:
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)
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

Commented:
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;
      }
}
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
Where is '$item' coming from?  If '$item' is blank, you're assigning '$qty' to a blank 'key'.  Maybe repeatedly.

Author

Commented:
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;
      }
}
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
Do yo have anything in your database yet?

Author

Commented:
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)
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
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.

Author

Commented:
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!!
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
Array 2 has both items.  If that's the one you're using, then your 'foreach' isn't working yet.

Author

Commented:
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

Author

Commented:
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 :)
Dave BaldwinFixer of Problems
CERTIFIED EXPERT
Most Valuable Expert 2014

Commented:
You're welcome.  Thanks for the points.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*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.