从Cookie数组中显示3个值?

时间:2015-12-08 20:53:14

标签: php html mysql search cookies

我想显示最后三次要显示的搜索。我设法让它通过使用cookie显示最后一个值,然后在搜索时显示它。但是,我如何再添加两个,当第四个添加时,它会推送最后一个?我认为这是一个数组,但不知道如何去做。该网站允许您在数据库中搜索汽车并将其显示在表格中。显示以下代码。如果您想要任何其他代码,请询问。

在search.php页面上:

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>

在car_results.php页面上:

$searchCar = $_POST['searchCar'];
  setcookie("searchCar", $searchCar);

  echo "<table>";
  echo "<h2>Previous Searches</h2>";
  echo "$searchCar<br><br>";

2 个答案:

答案 0 :(得分:0)

获得发布值后,将其存储在cookie中

if(isset($_POST['searchCar']))
    $v = isset($_COOKIE['searchCar'])? $_COOKIE['searchCar'] : "" ;
    $searchCar = $_POST['searchCar'].",".v; 
  else
    $searchCar = "";

setcookie("searchCar", $searchCar);

现在,当您需要显示最后三个搜索时,请使用:

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>";
}

答案 1 :(得分:0)

Cookies商店只能存储字符串,因此您需要以逗号分隔或json格式或类似的方式保存最后的搜索。

//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));

显示旧搜索只是迭代$last_searches

$searchCar = $_COOKIE['searchCar'];
$last_searches = json_decode($searchCar);
foreach($last_searches as $search){
    echo $search;
}

请不要依赖此代码,它只是一个概念;我自己没有测试过它