Multidimensional Session Arrays

Hello,
I have viewed some of the related threads but could not find out a solution.
What I want to do and how I plan it:
I have webpages with products along with their description. Each product has a star which a user can click to add the item to his/her wishlist.
There is a wishlist page where the user can view all the items in the wishlist. The product image, product name and product code will be displayed. I have planned of passing the productcode, productname and the associated imagefilename as hidden fields.
Since anonymous (not registered) users should have this option, I am not using database. Instead Session arrays are used.
I want that the products in the mywishlist page disappears once the user closes the window or a specified time has elapsed.
I can think of two ways. Really confused of either……Please suggest which one is ok and help me with the syntax also……
METHOD 1:
I would like to store the product info through hidden fields in an array. This array is created when a user clicks on the star to add an item to wishlist. This array be added further to a common/single session array. And the mywishlist page shows the contents of this session array.
HTML CODE:
<input type=“hidden” name=“myarray[0]” value=“Football Training” />
<input type=“hidden” name=“myarray[1]” value=“KSF-193” />
<input type=“hidden” name=“myarray[2]” value=“ksf193yb.png” />

PHP LOGIC:

<?php
session_start();

$_SESSION[wishlist]=“”;
//please suggest how to keep a session array empty initially and add other arrays too it later one by one.

$myArray = $_POST[‘myArray’];

if(isarray($myArray)) {

$_SESSION[wishlist]=array($myArray)

foreach($_SESSION[wishlist] as $wishlist)
{

echo ‘<tr>’;
foreach($wishlist as $item)
{
echo “<td>$item</td>”;
}
echo ‘</tr>’;
}

?>

METHOD 2
Something like this…….just the logic…….

<?php
while (isset($_POST[‘name’],$_POST[‘code’],$_POST[‘filename’])
{
$n=0;
$_SESSION[‘$n’][‘name’]=$_POST[‘name’];
$_SESSION[‘$n’][‘code’]=$_POST[‘code’];
$_SESSION[‘$n’][‘filenname’]=$_POST[‘filename’];
$n=$n+1;
}
?>

Use a database for this, not session variables.

Just create a visitor wishlist DB table, and you can use practically any method you want to track them ( IP address, for example )

Arout77, are you sure that session arrays should not be used? Other forum members also, please help.

Yes. It’s not that session is a bad idea, it’s just not ideal. Far from it…you’re going to go through all the trouble of managing sessions, and then they lose all that information when the session expires. Many people require several visits to build their wishlist / cart, because they shop around on other sites while browsing yours, or just don’t have time to do it all at once. When you store it in a database, people can keep their wishlist permanently, if they so choose; and it’s a heck of a lot less trouble than managing the sessions.
Or what about down the road when the site grows? You’re likely going to use memcached or something similar to handle sessions, and a bunch of wishlists stored in the session will quickly give undesired results. There’s more reasons, but seriously, just stuff it in the database; that’s what it’s there for.

And if you’re worried about performance…well, you’re hitting the database anyway to grab product prices and details, images, etc.

So, if I go for DB, so would I be storing the details of all anonymous users? Won’t the database become too huge?

That’s up to you…you can delete wishlists older than x-days or months, with a simple cron job run daily.
But if it’s properly setup, and maintained, there’s really no need to do that either, as long as you are on a decent server, not a $4/month shared host

So is the session id need to be stored in the db for anonymous users? Registered users has a username and password. The username will be the primary key if we go for registered users. but we want this to work for anonymous users. So what will be the primary of the table?

Please let me know how many tables should be there…

I have another question:
If I write a normal PHP script which acceprts data from the user and stores it in the databse …and this data can be retrieved on the mywishlist page showing all the items in wishlist FOR A PARTICULAR USER…The website could be used by multiple users at the same time and it is the same script (in a single PHP file) that will do same the job for all users at the same time…For this to work properly, do we just have to write a single line of code, that is, session_start(); ??

Will that do?

Can anyone guide me through this?

Hi

I agree with arout77 for the reasons outlined. I think (hope) i am correct in saying that most sites will use a cookie to ‘remember’ the wishlist for when you return. The cookie can just store a randomly generated code which you can use to match the database entry. Assuming you haven’t stored any user details it doesn’t need to be super secure as worst case scenario is that the wrong user might see a different list of items, but they won’t know who set them or get any personal data. (obviously best to make it as secure as you can though).

I’d prob just do a rand() for the id and check it isn’t already used in the database as an id otherwise, do another.

The nice thing with doing it this way is that you can add extras in over time. So a returning user could have a message saying ‘Hi you’ve put a few things in your wishlist 2 weeks ago, why not have a look and see if you still need them’ or you could even (if linked to user table)email a couple of weeks later ‘Hey you’ve got some things in your wishlist, just log back in to see what you’ve got. If you buy before XXXXX we’ll give you an extra 10% off’ etc.

So if you set a cookie you can return the shopping cart for a particular computer

If you set a cookie and link it to the user account then you can return the shopping cart for a user on the same computer whether they are logged in or not. And on a different computer as long, as they log in, you can return the cart (as the second computer doesn’t have a cookie set so you have to fall back to picking it up via the user id).

Going even further you could set up a query to look for common items in peoples wishlists and start making suggestions. IE Other people who bought X also bought Y
Data is king - the more you have the more you can understand what your users want. You can look for trends like why are people abandoning shopping carts with a certain product? are they finding it cheaper elsewhere? then adjust your marketing.

If you store in sessions you will not have this data.

hope that makes sense and is useful.

Thanks Noppy for the valuable insight. It helped a lot…I think what I want could be achieved with cookies…Let me explain:

Beside the product, I want to put an image with a star which a user can click to add the item to his wishlist. And I want that after the image is clicked once, it is replaced by another image showing a star with a tick which denotes that the item is added to the wishlist.

Now the question is that I want the user on that computer and only on that computer to see the second image (star with tick) for that particular product…and on other computers and the server it remains the same…I understand that this will be achieved by applying cookies…but do not know exactly how to do that…please help…

Am I going right?

Why are you building an OS Commerce package from scratch when there are several free ones in PHP out there such as Zencart (stay away from Magento, it’s bloatware)?

Even if you don’t want to use one, it would be useful to you to study them before building one to get an idea of the issues ahead of you. For example, suppose you have a product priced at $10. A customer puts it in their cart. Meanwhile an admin changes the price to $12. Which price do you use? You are legally bound to the $10 price - bait & switch is against the law in multiple jurisdictions. Compliance with local tax laws is also going to be a bear since the laws recently where changed to allow states to collect sales taxes on internet vendors. And then there’s the bear of credit card processing (Hint, NEVER store cc numbers - you are liable to monstrous fines if caught doing it regardless of whether your system ever gets compromised). These are not trivial issues from either a programmatic or legal standpoint.

The visitor wishlist table will be identical to member’s wishlist table, except you replace the username PK with whatever you are using to track them. There’s no ideal way to track an unregistered member. Of all the options, I’d just use their IP address. When you use session id’s, the PHP $_SESSION creates a cookie, so that is actually less reliable than using the IP address. With IP address method, the user can use any browser they have installed without losing changes, whereas the session cookie does not carry over from one browser to another. Either way, it’s not ideal, and you should be encouraging them to register.

Again, cookies are not a good idea. As mentioned above, it does not transfer from browser to browser. Secondly, cookies should never, ever contain any sensitive information. Third, cookies have a limit on how big they are allowed to be…it will be nearly useless for this. Keep everything in the database.

Again, cookies are not a good idea. As mentioned above, it does not transfer from browser to browser. Secondly, cookies should never, ever contain any sensitive information. Third, cookies have a limit on how big they are allowed to be…it will be nearly useless for this. Keep everything in the database.

Yep just use the cookie to reference the data in a database. I’m not 100% sure on using IP as the reference as most people are on dynamic ip’s so if the isp switches the IP or a user turns there router off for any reason it could change the ip. But either way they are both reference points to call data from a database not to actually store the data. Wouldn’t be that hard to check for a cookie and if none exists check for IP or visa versa.

As pointed out above though if you are doing things that involve personal data or payment you have to be very sure of what you are doing.

Hi

As suggested I am using cookies and storing it in DB… I have two tables-‘visitor’ and ‘wishlist’ tables…I have a visitor table having one colum , that is, visitor id…On clicking the wishlist mark, it is checked whether a cookie exists or not…if not, then a cookie is created and its value is set with a random no this is entered in the visitor table…and the product details are added to the wishlist table where the last column is visitorid which identifies that row is for that user…and if a cookie already exists, details for that user is inserted in the wishlist table directly with the lready set cookie value(random no.)…I have tried a lot but could not find the desired result…

At present the following error is displayed:
Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/indiaseo/public_html/buy/wishlist.php on line 21:

MY CODE:

balls.php (part):

<img src=“images/products/football/ksf193wr.png” alt=“” />
<span class=“pull-left”><form method=“post” action=“ac.php”><input type=“submit” id=“button” class="default /></span>
<input type=“hidden” name=“code” value=“KSF-193” />
<input type=“hidden” name=“name” value=“Football Training” />
<input type=“hidden” name=“imagepath” value=“images/products/football/ksf193wr.png” />
</form>

ac.php

<?php

header('Location: ’ . $_SERVER[‘HTTP_REFERER’]);
$code=$_POST[‘code’];
$name=$_POST[‘name’];
$imagepath=$_POST[‘imagepath’];

$host=“localhost”; // Host name
$username=“indiaseo_manager”; // Mysql username
$password=“manager123”; // Mysql password
$db_name=“indiaseo_talhanweb”; // Database name

mysql_connect(“$host”, “$username”, “$password”)or die(“cannot connect”);
mysql_select_db(“$db_name”)or die(“cannot select DB”);

if (isset($_COOKIE[“user”]))
{

$u=$_COOKIE[‘user’];
$query=“insert into wishlist values(‘’,‘$code’,‘$name’,‘$imagepath’,‘$user’)”;
mysql_query($query) or die (“ERROR: Wishlist details for”. $user." could not be added." . mysql_error());
$added=“<br />Congratulations! Wishlist details for user”. $user." is successfully added.<br />";
echo $added;

}
else
{
$expire=time()+606024*30;
$u=rand();
echo $u;
setcookie(“user”,$u, $expire);
echo "Your temporary id is ". $u;

$sql=mysql_query(“SELECT * FROM visitor WHERE visitorid=‘$u’”);
if(mysql_num_rows($sql)>=1)
{
$alreadyexists=“Sorry !! This name already exists”;
echo $alreadyexists;
}
else
{

$queryvisitor=“insert into visitor values(‘$u’)”;
mysql_query($queryvisitor) or die (“ERROR: Visitor could not be added.” . mysql_error());
$addedvisitor=“<br />Congratulations! Visitor is successfully added.<br />”;

echo $addedvisitor;

$query=“insert into wishlist values(‘’,‘$code’,‘$name’,‘$imagepath’,‘$u’)”;
mysql_query($query) or die (“ERROR: Wishlist details could not be added.” . mysql_error());
$added=“<br />Congratulations! Wishlist details for new user “.$u.” is successfully added.<br />”;
}
}

?>
<form method=“post” action=“wishlist.php”>
<input type=“hidden” value=“<?php echo $u; ?>” name=“coovalue” />
</form>

wishlist.php

<?php
$p=$_POST[‘coovalue’];

echo “Your Wishlist”;

mysql_connect(“localhost”, “indiaseo_manager”, “manager123”) or die(mysql_error());

mysql_select_db(“indiaseo_talhanweb”) or die(mysql_error());

$result = mysql_query(“SELECT * FROM wishlist where visitorid=‘$p’”) or die (mysql_error());
function creategroup()
{
echo “<table border=‘1’ width=100% align=‘left’>
<tr >
<th>Product</th>
<th>Code</th>
<th>Pic</th>
</tr>”;
$num=1;
while($group = mysql_fetch_array($result))
{
echo “<tr>”;
echo “<td>” . $group[‘productname’] . “</td>”;
echo “<td>” . $group[‘productcode’] . “</td>”;
echo “<td><img src='” . $group[‘productimagepath’] . “’ /></td>”;
$num++;
echo “</tr>”;
}

}

echo “</table>”;
creategroup();

?>

The price of things when I buy stuff from Amazon can change whilst it’s in my shopping cart, it’s the price when the order is placed that is charged.

Please be aware that the mysql_* extension is now deprecated as of the current version of PHP and will very likely be removed from the next 5.x version and will likely not be in PHP 6.x (when it eventually is released). You should migrate over to either the mysqli_* extension or to PDO. PDO is a better choice as it doesn’t tie you down so much to a particular database server software.

Once you have migrated you should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle.

Thanks…I will definitely try to migrate from mysql_* …but for the time being could you please tell if I am going right…with reference to the logic applied?

Can anyone help with the code logic…

Moreover I am not sure if I am using the right way to transfer cookie value from ac.php to wishlist.php through hidden field…

Kindly help…

You are missing parenthesis in the insert query.

$query=“insert into wishlistCOLOR=“#FF0000” [/COLOR]values(‘’,‘$code’,‘$name’,‘$imagepath’,‘$u’)”;

You also need to move the $result = mysql_query(“SELECT * FROM wishlist where visitorid=‘$p’”) or die (mysql_error()); inside of the creategroup() function. creategroup() has no idea what $result is, because it is outside the scope of the function.

Again, I advise to avoid using cookies for this.