Skip to content

Create an “add to shortlist” feature for your website – part 2

August 15, 2009

In part 1 we went through how to add individual records (in the form of IDs) to a shortlist. The IDs are stored in a session variable and are separated by commas. What we need to do now, is seperate those values out and use them to get some info, e.g. from a mySql database.

Firstly, we need to seperate the values in our string (stored in $_SESSION['shortlist']) based on the comma delimiter, and put the values into an array:

//put each id in $_SESSION['shortlist'] into shortlistitems array
$shortlistitems = explode(",", $_SESSION['shortlist']);
//get rid of null values
foreach ($shortlistitems as $key=>$id)
	{
  		if($id == "")
			{
				unset($shortlistitems[$key]);
			}
	}

A nice explanation of the explode function can be found at W3schools.

Now we have an array of individual IDs. If you were to output it using print_r($shortlistitems) it would look something like this:

Array
(
[0] => 1
[1] => 8
[2] => 97
[3] => 53
[4] => 111
[5] => 6
)

This is just a collection of IDs that don’t really mean much to our end user, so let’s use them to query a MySql database, and display some results in a table:


//start the table off...
echo "
<table>";
//loop through the array, returning data from the database based on $id for each shortlistitem.	Put results into a table
foreach ($shortlistitems as $k=>$id)
	{
		$sql = "SELECT * FROM yourtable WHERE id = ".$id;
		$query = mysql_query($sql) or die (mysql_error());
		while($result=mysql_fetch_array($query))
			{
				echo "
<tr>
<td>".$result['column1']."</td>
<td>".$result['column2']."</td>
<td>".$result['column3']."</td>
</tr>
";	

			}
	}
echo "</table>
";

Isn’t that nice? We’ve selected one or several rows of data from a database, based on the IDs that our end user has added to their shortlist. They can now see all their favourite widgets (or whatever) on our shortlist.php page. Basically, the above script says “for each shortlist item in our array, put the id into the $id variable, then select some data from a mySql database and display this in a table”. For some more explanation on using php with MySql see Angela Bradley’s PHP/MySQL Guide at About.com.

What if they want to remove items from their shortlist?

Add this to the top of your php script (i.e before you do anything with the $_SESSION[‘shortlist’] variable)

if ($_GET['shortlist']=="remove")
	{
		$_SESSION['shortlist'] = str_replace($_GET['id'].",","",$_SESSION['shortlist']);
	}

…and put a link like this in another cell in your row of results:

echo "
<td><a href='shortlist.php?shortlist=remove&id=".$id."'>remove from shortlist</a></td>
";

Components to this wee snippet:

  1. ($_GET[‘shortlist’]==”remove”)… This says that if we have shortlist=remove in our URL, carry out the code below. This is only set when we click on the ‘remove from shortlist’ link.
  2. str_replace… This finds the string we want to remove (i.e. the id plus the trailing comma) with “” (i.e. nothing) – thus deleting it from $_SESSION[‘shortlist’].
  3. a href=’shortlist.php?shortlist=remove&id=”.$id.”‘… By clicking on this link we are saying (a) run the remove from shortlist code, and (b) remove the id that relates to this row ($id).

The whole shebang…

<?php session_start()

//connect to MySql database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error()); //Note I usually put this in a seperate file and then use include() to call the file
mysql_select_db("Database_Name") or die(mysql_error()); 

//remove from shortlist
if ($_GET&#91;'shortlist'&#93;=="remove")
    {
        $_SESSION&#91;'shortlist'&#93; = str_replace($_GET&#91;'id'&#93;.",","",$_SESSION&#91;'shortlist'&#93;);
    }  

//put each id in $_SESSION&#91;'shortlist'&#93; into shortlistitems array
$shortlistitems = explode(",", $_SESSION&#91;'shortlist'&#93;);  

//get rid of null values
foreach ($shortlistitems as $key=>$id)
    {
        if($id == "")
            {
                unset($shortlistitems[$key]);
            }
    }  

//start the table off...
echo "
<table>";  

//loop through the array, returning data from the database based on $id for each shortlistitem. Put results into a table, include 'remove from shortlist' link
foreach ($shortlistitems as $k=>$id)
    {
        $sql = "SELECT * FROM yourtable WHERE id = ".$id;
        $query = mysql_query($sql) or die (mysql_error());
        while($result=mysql_fetch_array($query))
            {
                echo "
<tr>
<td>".$result['column1']."</td>
<td>".$result['column2']."</td>
<td>".$result['column3']."</td>
<td><a href='shortlist.php?shortlist=remove&id=".$id."'>remove from shortlist</a></td>
</tr>
";    

            }
    }
echo "</table>
";
?>

And there you go. PHP session_end.

Advertisements
2 Comments leave one →
  1. August 15, 2009 1:03 pm

    This is just the bones of how this works – i.e. displaying and editing the shortlist. What I will be doing for http://www.perfectvenue.co.nz is using the list to allow end users to email multiple venues at the same time.

  2. May 27, 2011 12:16 am

    Nice one Kylie. Very useful for my Clients Classified site. Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: