I have a holiday rental listing site and I have a MYSQL database with 25 properties on it. I would like to create an “add to shortlist” feature and know (think) I need to use cookies / php to do this. Can anyone point me at a resource that will get me going please?
Cookies in my personal opinion wouldn’t be the best way to store a list as if a member clears there browser out that cookie will get deleted along with the values needed to populate the list.
My solution would be to use PHP and MySQL to set and get the list for the user based on their IP or a stored cookie set in their browser. Look at the code below for examples of how i would do it.
Get the short list
/**
* Create a new MySQLi connection to the server
*/
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DATABASE);
if ($db->connect_error) {
die('An error has occurred while trying to connect to the MySQL server<br /><br />' . $db->connect_error);
}
/**
* Get some information about the user
*/
$user = isset($_COOKIE['user_storage']) ? $_COOKIE['user_storage'] : $_SERVER['REMOTE_ADDR'];
if (!$result = $db->query("SELECT list FROM short_lists WHERE user = '$user'")) {
die('A MySQL error has occurred!<br /><br />' . $db->error);
}
if ($result->num_rows) {
// Fetch the row and unserialize the result
list($theList) = $result->fetch_row();
$theList = unserialize($theList);
$select = '<select name="short_list" multiple="multiple" size="5">';
foreach ($theList as $k => $v) {
$select .= '<option value="' . $k . '">' . $v . '</option>';
}
$select .= '</select>';
echo $select;
}
Set the short list
/**
* Create a new MySQLi connection to the server
*/
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DATABASE);
if ($db->connect_error) {
die('An error has occurred while trying to connect to the MySQL server<br /><br />' . $db->connect_error);
}
/**
* Get some information about the user
*/
$user = isset($_COOKIE['user_storage']) ? $_COOKIE['user_storage'] : $_SERVER['REMOTE_ADDR'];
if (isset($_POST['the_list']) && sizeof($_POST['the_list']) > 0) {
// Serialize the $_POSTED list for database entry
$theList = serialize($_POST['the_list']);
if (!$result = $db->query("INSERT INTO short_lists (`list`,`user`) VALUES('$theList','$user')")) {
die('A MySQL error has occurred!<br /><br />' . $db->error);
}
}
When you read the cookie data be very aware that a user can tamper cookie data, so keep things really simple and just set a short list of integers, then check each integer is valid before acting on them. Typecasting the value to an integer is the easiest way like so:
// you split your cookie into an array of values whose
// real values remain a bit circumspect at this point
$dodgy[0] = 12;
$dodgy[1] = 'bad string;-- delete * from venues';
$dodgy[2] = '12';
foreach( $dodgy as $val ){
if( (int)$v === 0 ){
// abort this operation
}else{
echo (int)$v . '<br />' . PHP_EOL ;
}
}