简体   繁体   中英

How can I save and echo a users 5 recent searches

I have an ajax search box on my site that allows the user to search my database for content. What I would like to know is how to save a users 5 most recent submitted searches with sessions and echo them out live on the page

Simple solution:

You need to build it.

Specifically, if you want to use SESSION your function needs to do the following:

  1. Create an SESSION array of (5)
  2. On each AJAX call, your search.php should also push the POST onto the array.
  3. On search #6, you need to push the index of each element +1, popping the 1st and adding the 6th.

For each Nth element after 5 pop the 1st, push the index of each element +1 and add the Nth.

On your home page, or wherever you are going to see the results, you will just need to:

<div>
<?
echo "Most recent searches: 1. ".$_SESSION[searches][0]."<br>
                            2. ".$_SESSION[searches][1]."<br>
                            3. ".$_SESSION[searches][2]."<br>
                            4. ".$_SESSION[searches][3]."<br>
                            5. ".$_SESSION[searches][4]."<br>"; ?>
</div>

If you mean across multiple pages, you can do it client-side by saving the searches in a cookie and retrieving them via javascript and adding them to the page by the search box.

If you only need it for the current page, then you can update a local javascript array variable after each search (remove oldest entry, add newest).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM