I would like to display the last three searches that were made to be displayed. I have managed to get it to display the last value by using a cookie, which then displays it when a search is made. However, how do I add two more, and when a fourth is made, it pushes the last one off? I presume this is with an array, but have no idea how to go about it. The website allows you to search for cars in the database and display them in a table. Displaying the code just for this below. If you would like any of the other code, just ask.
On search.php page:
if(isset($_COOKIE['searchCar']))
$searchCar = $_COOKIE['searchCar'];
else
$searchCar = "";
<h2>Search for Cars</h2>
<form action="cars_results.php" method="post">
<p>Enter Car Make or Model: <input type="text" name="searchCar" value="<?=$searchCar?>"></p>
<p><input type="submit" value="Search"></p>
</form>
On car_results.php page:
$searchCar = $_POST['searchCar'];
setcookie("searchCar", $searchCar);
echo "<table>";
echo "<h2>Previous Searches</h2>";
echo "$searchCar<br><br>";
When you get a posted value, store it in the cookie
if(isset($_POST['searchCar']))
$v = isset($_COOKIE['searchCar'])? $_COOKIE['searchCar'] : "" ;
$searchCar = $_POST['searchCar'].",".v;
else
$searchCar = "";
setcookie("searchCar", $searchCar);
Now when you need to display last three searches use this:
if(isset($_COOKIE['searchCar'])){
$searchCar =$_COOKIE['searchCar'];
$k = explode(",", $searchCar);
$val1 = $k[0];
$val2 = $k[1];
$val3 = $k[2];
echo "<table>";
echo "<h2>Previous Searches</h2>";
echo "$val1<br><br>";
echo "$val2<br><br>";
echo "$val3<br><br>";
}
Cookies store can only store strings, so you will need to save the last searches in a comma separated or json format or something similar.
//Read current cookie
$searchCar = $_COOKIE['searchCar'];
//decode the cookie
$last_searches = json_decode($searchCar);
//add current search term to cookie array
$last_searches[] = $_POST['searchCar'];
//Do Search
//Send Cookie
setcookie("searchCar", json_encode($searchCar));
to show old searches just iterate over $last_searches
$searchCar = $_COOKIE['searchCar'];
$last_searches = json_decode($searchCar);
foreach($last_searches as $search){
echo $search;
}
Please do not rely on this code, it's just a concept; i haven't tested it myself