一、创建数据库表
CREATE TABLE site_visits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
visit_time DATETIME NOT NULL,
ip_address VARCHAR(45) NOT NULL
);
二、PHP处理脚本(save_visit.php)
<?php
// 数据库配置,需要提前配置好php,Mysql环境,可以下载phpstudy
$servername = "localhost";
$username = "your_username";//用户名
$password = "your_password";//密码
$dbname = "your_database";//数据库
// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// 获取访问者IP地址
$ip = $_SERVER['REMOTE_ADDR'];
// 获取当前时间
$visit_time = date('Y-m-d H:i:s');
// 预处理SQL语句防止SQL注入
$stmt = $conn->prepare("INSERT INTO site_visits (visit_time, ip_address) VALUES (?, ?)");
$stmt->bind_param("ss", $visit_time, $ip);
// 执行并检查结果
if ($stmt->execute()) {
// 成功写入后可以跳转或继续显示页面
} else {
echo "Error: " . $stmt->error;
}
$stmt->close();
$conn->close();
// 以下是HTML内容
?>
<!DOCTYPE html>
<html>
<head>
<title>访问记录</title>
</head>
<body>
<h1>欢迎访问我们的网站</h1>
<p>您的访问信息已被记录</p>
</body>
</html>