php 搜索记录如何实现

小老鼠
发布: 2024-08-04 07:47:00
原创
349人浏览过
通过在数据库中创建表、执行查询和存储搜索项,可以实现 PHP 搜索记录。前端使用 HTML 和 JavaScript 显示搜索记录,并允许用户重新访问页面。

php 搜索记录如何实现

如何实现 PHP 搜索记录

引入
搜索记录是用户体验的重要组成部分,它允许用户轻松地查找他们的搜索查询历史记录,并重新访问过去感兴趣的页面。本文介绍了如何在 PHP 中实现搜索记录功能。

数据库表
首先,我们需要创建一个数据库表来存储搜索记录。表结构如下所示:

CREATE TABLE search_history (
  id INT NOT NULL AUTO_INCREMENT,
  user_id INT NOT NULL,
  query VARCHAR(255) NOT NULL,
  created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id)
);
登录后复制

查询
要显示用户的搜索记录,我们需要执行以下查询:

立即学习PHP免费学习笔记(深入)”;

$userId = 1; // Replace with the actual user ID
$stmt = $pdo->prepare("SELECT query, created_at FROM search_history WHERE user_id = ? ORDER BY created_at DESC");
$stmt->execute([$userId]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
登录后复制

存储
要存储新的搜索查询,请执行以下操作:

$userId = 1; // Replace with the actual user ID
$query = 'PHP search records'; // Replace with the actual search query
$stmt = $pdo->prepare("INSERT INTO search_history (user_id, query) VALUES (?, ?)");
$stmt->execute([$userId, $query]);
登录后复制

前端
在前端,可以使用 HTML 和 JavaScript 来显示搜索记录并允许用户重新访问页面。以下是简单的示例:

<ul id="search-history">
{% for result in results %}
  <li><a href="{{ result.query }}">{{ result.query }}</a><span class="timestamp">{{ result.created_at }}</span></li>
{% endfor %}
</ul>
登录后复制
// Get the search history element
const historyElement = document.getElementById('search-history');

// Iterate through the results and create list items
for (let i = 0; i < results.length; i++) {
  const result = results[i];

  // Create the list item
  const li = document.createElement('li');

  // Create the anchor tag
  const a = document.createElement('a');
  a.href = result.query;
  a.textContent = result.query;

  // Create the timestamp span
  const span = document.createElement('span');
  span.classList.add('timestamp');
  span.textContent = result.created_at;

  // Append the anchor tag and timestamp span to the list item
  li.appendChild(a);
  li.appendChild(span);

  // Append the list item to the search history element
  historyElement.appendChild(li);
}
登录后复制

通过遵循这些步骤,您可以轻松地在 PHP 中实现搜索记录功能,从而为您的用户提供更好的体验。

以上就是php 搜索记录如何实现的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号