Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Server-side Scripting _ sessions trouble

Posted by: Mindapolis Nov 9 2011, 06:54 PM

I'm having problems with sessions. if I post the code could someone please help me?

Posted by: Darin McGrew Nov 10 2011, 02:10 AM

What kinds of "problems with sessions"?

You're better off learning how to debug your own programs. We can help with that. But it's unlikely that we'll be able to find the problem just by looking at your code.

Posted by: Frederiek Nov 10 2011, 02:35 AM

These might help:
http://devzone.zend.com/node/view/id/627
http://www.php.net/manual/en/book.session.php

Posted by: Mindapolis Nov 10 2011, 09:57 AM

Hi, first of all I'm really not trying to get anyone to do my work. I have read many articles on sessions but it 's just not clicking how to transfer information from onepage to another. For example, I'm working on a website that I need to be able to be able to transfer the product name and quantity from the product page to the checkout page. On the products page if I click "order treats" it will go to the checkout page but it will not transfer the quantity. I can display the product page code but the checkout page code is long so I will display only necessary code.

CODE


<?php
session_start();
if(isset($_POST['empty']) || !isset($_SESSION['cart']))
    $_SESSION['cart'] = array();  //if a cart is clear or doesn't exist yet
if(isset($_POST['quantity'])  && isset($_POST['product_title']))
    {
        $product_title = $_POST['product_title'];
    $quantity = $_POST['quantity'];

$cart = $_SESSION['cart'];
if( isset($cart[$product_title]) ){
        // If so, add quantity to it.
        $cart[$product_title] += $quantity;
$_SESSION['cart']=$cart;// ADDED LINE
}
    else{
        // Otherwise, set it to the quantity
        $cart[$product_title] = $quantity;
$_SESSION['cart']=$cart;// ADDED LINE

    // Destroy the reference to $cart to avoid acidentally screwing with it elsewhere in the script
    unset( $cart );
}
}        
require_once("functions.php");
DatabaseConnection();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
td {
    border-top-style: solid;
    border-right-style: solid;
    border-bottom-style: solid;
    border-left-style: solid;
    border-top-color: #30C;
    border-right-color: #30C;
    border-bottom-color: #30C;
    border-left-color: #30C;
}
#productCatalog {
    width:400px;  
    margin-right: auto;
    margin-left: auto;
}
</style>
<link href="doggyTreats.css" rel="stylesheet" type="text/css" />
</head>

<body>
<?php
logo();
navBar();
echo "<div id=\"productCatalog\">";
echo "<form action=\"checkOut.php\" method=\"post\" name=\"catalog\">";
  
DatabaseConnection();  

  $query = "SELECT * FROM treats";
        $result_set = mysql_query($query) or die(mysql_error());
$i = 0;

        echo "<table>";
        while ($row = mysql_fetch_array($result_set))
        {
        echo"<tr><td width=\"2s00px\"><img src=\"{$row['product_pic']}\" /></td><td width=\"200px\">{$row['product_title']}.<br /><br />{$row['product_Description']}.<br /> Price:  \${$row['price']}{$row['pricePer
        ']}.<br /><br />Quantity <input name=\"quantity\" type=\"text\" size=\"2\" /></td></tr>";
        }
        echo "<tr>";
            echo "<td><input name=\"submit\" type=\"submit\" value=\"Proceed to Checkout\" />";
        echo "</table>";    
        echo "</form>";
echo "</div>";
footer();
?>
</body>
</html>'


[code]
<?php
session_start();
if(isset($_POST['empty']) || !isset($_SESSION['cart']))
$_SESSION['cart'] = array(); //if a cart is clear or doesn't exist yet
if(isset($_POST['quantity']) && isset($_POST['product_title']))
{
$product_title = $_POST['product_title'];
$quantity = $_POST['quantity'];

$cart = $_SESSION['cart'];
if( isset($cart[$product_title]) ){
// If so, add quantity to it.
$cart[$product_title] += $quantity;
$_SESSION['cart']=$cart;// ADDED LINE
}
else{
// Otherwise, set it to the quantity
$cart[$product_title] = $quantity;
$_SESSION['cart']=$cart;// ADDED LINE

// Destroy the reference to $cart to avoid acidentally screwing with it elsewhere in the script
unset( $cart );
}
}
require_once("functions.php");
DatabaseConnection();
?>

html code
<tr>
<ul>
<?php
foreach($_SESSION['cart'] as $product_title => $quantity)
{
echo "<li>$product_title $quantity</li>";
}
print_r($_SESSION['cart']);
?>
</ul>
</tr>

Posted by: Darin McGrew Nov 10 2011, 12:06 PM

In a sense, the point of sessions is that you don't have to transfer information from one page to another. Instead, you transfer information to the server. That information is stored on the server, with the session ID as the key. Later, when another page needs that information, it uses the session ID to look it up.

So, how does the "order treats" link/button/whatever transfer information to the server? How does the server associate that information with the session ID? Have you tested the software to see whether that is happening correctly?

Posted by: Mindapolis Nov 10 2011, 12:24 PM


I'm sorry, but could you rephrase these questions?
So, how does the "order treats" link/button/whatever transfer information to the server? How does the server associate that information with the session ID?


QUOTE(Darin McGrew @ Nov 10 2011, 12:06 PM) *

In a sense, the point of sessions is that you don't have to transfer information from one page to another. Instead, you transfer information to the server. That information is stored on the server, with the session ID as the key. Later, when another page needs that information, it uses the session ID to look it up.

So, how does the "order treats" link/button/whatever transfer information to the server? How does the server associate that information with the session ID? Have you tested the software to see whether that is happening correctly?


Posted by: Darin McGrew Nov 10 2011, 02:27 PM

When the user clicks on the "order treats" link/button/whatever, what happens on the server? What do your server-side programs do?

Posted by: Mindapolis Nov 10 2011, 02:41 PM

it takes them to the checkout page and displays array() under the navbar



Posted by: Darin McGrew Nov 10 2011, 04:08 PM

When do you update the session data to include the treats the user ordered?

Posted by: Mindapolis Nov 14 2011, 11:09 AM

I'm sorry I'm not understanding your question; however, over the weekend I was able to understand how to transfer one form element from one page to about another, but I can't understand how to transfer a set of variables from one page to another. I know I need need to use a foreach loop, but its not working. here 's what I have

product.php

CODE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$errors=array();
if(isset($_POST['submit']))
{
    if(empty($_POST['name'])){
    $errors['name']=" put your name";
    }
}
?>    
<form action="checkOut.php" method="post" name="test">  
<?php if(isset($errors['name'])){ echo $errors['name']."<br />"; } ?>
Name:  <input name="name" type="text" size="10" maxlength="15" value="<?php if(isset($_POST['name'])){ echo "$_POST[name]"; } ?>" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
<input name="submit" type="submit" value="Submit" />
</form>
</body>
</html>


checkout.php
CODE

<?php
session_start();
$_SESSION['name']=$_POST['name']; //gets users input
$_SESSION['quantity']=$_POST['quantity'];
?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table>
<tr>
<?php
$order=array($quantity);
    foreach($order as $value){
    echo $value;
}
?>
</tr>
</table>
</body>
</html>

Posted by: Darin McGrew Nov 14 2011, 12:22 PM

What do you mean by "transfer a set of variables from one page to another"? How is that different from "transfer one form element from one page to about another"?

Posted by: Brian Chandler Nov 14 2011, 01:28 PM

QUOTE
its not working. here 's what I have


Do you mean "This is my attempt to write the program myself"?? In which case I suggest the first thing to do is to study how to lay a program out. Currently it's unreadable, because the php angle brackets, html syntax etc is all jumbled up.

I don't understand quite what you mean by "transferring variables". Esssentially you can't do such a thing, except by using forms. A form transfers values for user input to the "action" page it is sent to.

Looking at the 'checkout' page; I don't see what the session stuff is for. Perhaps you should try to write a simple page including a form, and nothing else, which transfers user input to a second page that prints it out.

In particular there are many mysteries here... what is $order=array($quantity); for? As far as I can see $quantity is an undefined variable at this point, so this will probably make $order into an empty array. But I have no idea quite what you are trying to do.


CODE

<table>
<tr>
<?php
$order=array($quantity);
    foreach($order as $value){
    echo $value;
}
?>
</tr>


Notice also that if the bit of php outputs 'XXX' you will get

CODE

<table>
<tr>
XXX
</tr>


which is invalid html. <tr> must include at least one <td>.


Posted by: Mindapolis Nov 14 2011, 01:41 PM

Brian, why do you have the need to make belittling comments to someone who is already feeling stupid about this topic? Please stop it

Posted by: Mindapolis Nov 14 2011, 02:16 PM

Take the code for example. I know if you want to transfer the name over to the checkout page you would put

CODE
  echo $_SESSION['name'];
. I tried putting
CODE
$_SESSION['quantity'];
but the quantity wouldn't transfer. Besides if there is more than one quantity don't I want to use a foreach loop?


QUOTE(Darin McGrew @ Nov 14 2011, 12:22 PM) *

What do you mean by "transfer a set of variables from one page to another"? How is that different from "transfer one form element from one page to about another"?


CODE

<?php
session_start();
$_SESSION['name']=$_POST['name']; //gets users input
$_SESSION['quantity']=$_POST['quantity'];
?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table>
<tr>
<?php  echo $_SESSION['name'];
}
?>
</tr>
</table>
</body>
</html>

Posted by: Ephraim F. Moya Nov 14 2011, 08:05 PM

Here's a VERY basic tutorial.

http://www.tizag.com/phpT/phpsessions.php

A good place to start.

Posted by: Brian Chandler Nov 14 2011, 11:42 PM

QUOTE(Mindapolis @ Nov 15 2011, 03:41 AM) *

Brian, why do you have the need to make belittling comments to someone who is already feeling stupid about this topic? Please stop it


I'm not making "belittling" comments, unless you think I shouldn't say "jumbled up", but rather "less than optimally laid out".

I see no reason to feel stupid. I think the real problem is that you have not realised at all that understanding programming is quite a big (understatement) job. To a certain extent you can manage to produce (e.g.) html documents by a sort of incremental guess-and-learn process, but for programming I think you really need to go off an study some elementary primers on "what is a program".

But because you refuse to answer questions like "Do you understand XYZ?" or "What do you understand PQW to mean?" any help people try to offer is totally hit-and-miss.

Anyway, that's trying to be helpful.

Posted by: Brian Chandler Nov 14 2011, 11:49 PM

QUOTE(Mindapolis @ Nov 15 2011, 04:16 AM) *

Take the code for example. I know if you want to transfer the name over to the checkout page you would put

CODE
  echo $_SESSION['name'];


I tried putting
CODE
$_SESSION['quantity'];


but the quantity wouldn't transfer. Besides if there is more than one quantity don't I want to use a foreach loop?


No, writing echo $_SESSION['name']; does not transfer anything anywhere. It writes the value of this array element to the current output.

Look, I do not think you have understood sessions *at all*. You do not need to use sessions for simple form handling. I suggest you write the following as a starter:

A page including a form with one input field (text) and a submit button.
A php script called by this form which prints the value of the input field.

If you do this successfully it should mean you have understood the basics of forms. If you need specific help, ask. Until you have done this you will get nowhere trying to use sessions, which are rather more complicated (and in general not essential at all).

Posted by: Mindapolis Nov 15 2011, 09:18 AM

I'm sorry but you are wrong. using echo $_SESSION['name']; did transfer the name from one page to another.

The code I displayed is on a small scale. What I'm having trouble understanding is how to transfer multiple quantities.

Posted by: Ephraim F. Moya Nov 15 2011, 10:07 AM

QUOTE(Mindapolis @ Nov 15 2011, 07:18 AM) *

I'm sorry but you are wrong. using echo $_SESSION['name']; did transfer the name from one page to another.

The code I displayed is on a small scale. What I'm having trouble understanding is how to transfer multiple quantities.


In the top of each program that uses sessions do:

session_start();

This prepares the program to use SESSIONS by getting and sending a cookie containing a pointer into the local SESSION database to the visitor.

During the program add enough $_SESSIONS['xxx']s to carry ALL the data you want for the next time this visitor from this particular domain requests a page.

When you fall off the bottom of the program ALL the data that is in the SESSIONS array is stored locally and keyed to the cookie sent above.

in the meantime many or none other visitors come to get pages from you using a different or no cookie. This particular SESSION array is NOT accessed for them. Their own SESSION array (or none) is accessed.

Finally a visitor with the right cookie shows up and based on that cookie the local SESSION database is read and the SESSION array is filled in.

So, if a SESSION entry contains one value or MANY values doesn't matter.

There are rules about what a SESSION entry can contain, though. You need to learn them. Read the SESSION stuff on php.net over and over until you understand it well.

Brian is right. You're trying to run before you know how to crawl. Start with basic php, go to php with classes, then go to SESSIONS.

Posted by: Mindapolis Nov 15 2011, 01:09 PM

I understand about crawling before running and that 's what I'm doing. I know how to transfer one variable to multiple pages but I dont understand how to transfer arrays from one page to another. I found this example on http://www.phpriot.com/articles/intro-php-sessions/7 I understand everything except what elements to put in the array since the elements are the user 's input here 's what I have so far.

when I run this I get

Warning: Invalid argument supplied for foreach() in /home/content/a/u/n/auntievics/html/test/checkOut.php on line 18

CODE

<?php
session_start();
$quantity_desired=array($quantity);
$_SESSION['quantity']=$quantity_desired;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$errors=array();
if(isset($_POST['submit']))
{
    if(empty($_POST['name'])){
    $errors['name']="dipshit, put your name";
    }
}
?>    
<form action="checkOut.php" method="post" name="test">  
<?php if(isset($errors['name'])){ echo $errors['name']."<br />"; } ?>
Name:  <input name="name" type="text" size="10" maxlength="15" value="<?php if(isset($_POST['name'])){ echo "$_POST[name]"; } ?>" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
<input name="submit" type="submit" value="Submit" />
</form>
</body>
</html>


CODE

<?php
session_start();

//$_SESSION['name']=$_POST['name']; //gets users input
//$_SESSION['quantity']=$_POST['quantity'];
?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table>
<tr>
<td>  
<?php
foreach($_SESSION['quantity'] as $key=>$value)
//  echo $_SESSION['name'];
  echo $_SESSION['quantity'];  
?>
</td>
</tr>
</table>
</body>
</html>


Posted by: Mindapolis Nov 15 2011, 01:11 PM

I will look into classes. That is one thing we did not cover in class.

Posted by: Ephraim F. Moya Nov 15 2011, 02:02 PM

QUOTE(Mindapolis @ Nov 15 2011, 11:09 AM) *

I understand about crawling before running and that 's what I'm doing. I know how to transfer one variable to multiple pages but I dont understand how to transfer arrays from one page to another. I found this example on http://www.phpriot.com/articles/intro-php-sessions/7 I understand everything except what elements to put in the array since the elements are the user 's input here 's what I have so far.

when I run this I get

Warning: Invalid argument supplied for foreach() in /home/content/a/u/n/auntievics/html/test/checkOut.php on line 18

CODE

<?php
session_start();
$quantity_desired=array($quantity);
$_SESSION['quantity']=$quantity_desired;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$errors=array();
if(isset($_POST['submit']))
{
    if(empty($_POST['name'])){
    $errors['name']="dipshit, put your name";
    }
}
?>    
<form action="checkOut.php" method="post" name="test">  
<?php if(isset($errors['name'])){ echo $errors['name']."<br />"; } ?>
Name:  <input name="name" type="text" size="10" maxlength="15" value="<?php if(isset($_POST['name'])){ echo "$_POST[name]"; } ?>" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
quantity <input name="quantity" type="text" size="2" /><br />  
<input name="submit" type="submit" value="Submit" />
</form>
</body>
</html>


CODE

<?php
session_start();

//$_SESSION['name']=$_POST['name']; //gets users input
//$_SESSION['quantity']=$_POST['quantity'];
?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table>
<tr>
<td>  
<?php
foreach($_SESSION['quantity'] as $key=>$value)
//  echo $_SESSION['name'];
  echo $_SESSION['quantity'];  
?>
</td>
</tr>
</table>
</body>
</html>



It turns out that you can't point to an array because the chances are that the array will be different next time thru. So you have to, instead, individually save the elements of the array that you want.

That's why I told you to investigate what the rules are for SESSION data.


Posted by: Ephraim F. Moya Nov 15 2011, 03:23 PM


It turns out that you can't point to an array because the chances are that the array will be different next time thru. So you have to, instead, individually save the elements of the array that you want.

That's why I told you to investigate what the rules are for SESSION data.

In your case your foreach statement is completely nonsensical. Foreach applies to an array and you're applying it to a string.

That's why people keep telling you that you need to learn php.

You're like a newborn crying and peeing instead of crawling to the next subject. Basic php includes learning how to handle arrays, not to mention recognizing correct instructions from faulty instructions.

BTW, setting a SESSION variable then printing it in the same program proves NOTHING about transfer of data.


Posted by: Ephraim F. Moya Nov 16 2011, 03:22 PM

What crappy board software. Why won't it format tabs?

You know, wordpress does better and it's free!

I'll make a page of my post and link to that here. Maybe that's allowed.

Posted by: Darin McGrew Nov 16 2011, 05:51 PM

All the forums I frequent implement some version of BBCode. I don't recall any of them doing anything with tabs. (Although you did get me to look up what WordPress does with tabs...)

Posted by: Ephraim F. Moya Nov 16 2011, 07:23 PM

Here's my first cut at explaining SESSIONS interactions.

http://moya.us/Sessions.php

This is a schematic and isn't point by point.

Posted by: Brian Chandler Nov 17 2011, 03:27 AM

Ephraim said:

QUOTE
It turns out that you can't point to an array because the chances are that the array will be different next time thru. So you have to, instead, individually save the elements of the array that you want.


I don't understand this. (I haven't actually used sessions, but I assume the $_SESSION superglobal is essentially a persistent variable.)

If you just mean storing an array in $_SESSION, that appears to be OK. What do you mean by "point to"? If you mean a _reference_, then obviously storing pointers would be no good. But you can simply copy the whole array, no?

Posted by: Ephraim F. Moya Nov 17 2011, 10:03 AM

QUOTE(Brian Chandler @ Nov 17 2011, 01:27 AM) *

Ephraim said:

QUOTE
It turns out that you can't point to an array because the chances are that the array will be different next time thru. So you have to, instead, individually save the elements of the array that you want.


I don't understand this. (I haven't actually used sessions, but I assume the $_SESSION superglobal is essentially a persistent variable.)

If you just mean storing an array in $_SESSION, that appears to be OK. What do you mean by "point to"? If you mean a _reference_, then obviously storing pointers would be no good. But you can simply copy the whole array, no?


$array2 = $_SESSIONS; doesn't do it. You have to do: $var_x_y = $_SESSIONS[x][y]; for each x and y. I believe I pointed this out above. When you go to use these data you'll have to re-build the old $_SESSIONS array from the pieces you get.

Also, don't forget that sessions work on the NEXT time through for any particular program. $_SESSIONS is a php 'resource identifier' for the $_SESSIONS array which eventually points to the current array. So if the program saves this data structure in the sessions database the NEXT time the program executes the actual array may a) not have been generated, b) been generated but differently than last time or c) the data this time is in a different place than the resource identifier thinks. So you can't save a resource id, of any kind, in an $_SESSIONS array.

Persistence in php is ONLY while the <u>current</u> program is executing. Isn't that the way for ALL programs?

Here I'm on shaky ground! I don't know how actual php does things but I think this is a pretty good guess:

PHP uses 'object' ids for all the variables of a program, not the actual variable. So if you want to add $two and $three
php doesn't actually keep '2' in $two and '3' in $three instead $two is an 'object id' that describes an integer, 8bits, at mem xx, value=2, etc as is $three and as is $sum, etc.

So $sum = $two + $three; is a rather long dance.

Posted by: Frederiek Nov 17 2011, 11:34 AM

Mindapolis, get yourself the book "PHP & MySQL Web Development" by Luke Welling and Laura Thompson (it's currently at its fourth edition).

Better yet, there's even a PDF version of the book (second edition) at http://levhita.net/archivos/PHP%20and%20MySQL,%20Web%20Development.pdf .

And follow the sample application of Bob's Auto Parts, at the beginning of the book.
Although it's all about PHP 4, the essence is there for what you try to achieve.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)