是否显示Cookie数组中的3个值?

问题描述 投票:0回答:2

我想显示要显示的最后三个搜索。我设法通过使用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>";
php html mysql search cookies
2个回答
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;
}

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


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>";
}
© www.soinside.com 2019 - 2024. All rights reserved.