服务器玩法系列(4)——搭建记事本(原创)

演示站:https://note.venuslee.cn/
代码还有bug,但是我不想修啦!

一 创建数据库

连接到MySQL:

mysql -u root -p

创建数据库(如果尚未创建):

CREATE DATABASE notebook;
USE notebook;

创建表

-- 创建 users 表
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL UNIQUE,  -- 设置更长的用户名长度
    password VARCHAR(255) NOT NULL
);

-- 创建 notes 表
CREATE TABLE notes (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id INT NOT NULL,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,  -- 默认当前时间戳
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE  -- 外键约束,删除用户时删除相关笔记
);

-- 创建 visits 表
CREATE TABLE visits (
    id INT AUTO_INCREMENT PRIMARY KEY,
    count INT NOT NULL
);

二 源代码

1.0

<?php
// 数据库连接配置
$servername = "localhost";  // 数据库主机
$username = "notebook";     // 数据库用户名
$password = "eYbFYJSHpHP2HRXw"; // 数据库密码
$dbname = "notebook";       // 数据库名称

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查数据库连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);  // 连接失败则输出错误信息并终止脚本执行
}

// 启动会话
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = null;  // 未登录则将 user_id 设置为 null
}

// 用户注册处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    $username = $_POST['username'];  // 获取用户输入的用户名
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // 对密码进行哈希处理

    // 检查用户名是否已存在
    $check_sql = "SELECT COUNT(*) FROM users WHERE username = ?";  // 检查用户名是否已存在
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("s", $username);
    $check_stmt->execute();
    $check_stmt->bind_result($count);  // 获取查询结果
    $check_stmt->fetch();
    $check_stmt->close();

    if ($count > 0) {
        // 用户名已存在,提示用户
        echo "<script>alert('用户名已存在,请使用其他用户名!');</script>";
    } else {
        // 用户名不存在,可以注册
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";  // 插入新用户数据
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $username, $password);
        if ($stmt->execute()) {
            // 注册成功,提示用户登录
            echo "<script>alert('注册成功,请登录!');</script>";
        } else {
            // 注册失败,显示错误信息
            echo "<script>alert('注册失败:" . $stmt->error . "');</script>";
        }
        $stmt->close();
    }
}

// 用户登录处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) {
    $username = $_POST['username'];  // 获取用户名
    $password = $_POST['password'];  // 获取密码

    // 查询用户名对应的用户数据
    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // 用户存在,验证密码
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];  // 登录成功,将用户 ID 存入会话
            // echo "<script>alert('登录成功!');</script>";
        } else {
            // 密码错误
            echo "<script>alert('密码错误!');</script>";
        }
    } else {
        // 用户不存在
        echo "<script>alert('用户不存在!');</script>";
    }
    $stmt->close();
}

// 保存笔记处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_note']) && $_SESSION['user_id']) {
    // 获取标题,如果没有标题则为 null
    $title = isset($_POST['title']) && !empty($_POST['title']) ? $_POST['title'] : null;
    $content = $_POST['content'];  // 获取笔记内容
    $user_id = $_SESSION['user_id'];  // 获取当前用户 ID

    // 去除多余的换行符
    $content = trim($content);

    // 转义用户输入,防止 XSS 攻击
    $title = $title !== null ? htmlspecialchars($title, ENT_QUOTES, 'UTF-8') : ''; 
    $content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

    // 插入笔记数据
    $sql = "INSERT INTO notes (user_id, title, content) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iss", $user_id, $title, $content);
    if ($stmt->execute()) {
        // 保存成功
        // 可以根据需要返回成功提示
    } else {
        // 保存失败,显示错误信息
        echo "<script>alert('保存失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 编辑笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_note_id']) && isset($_POST['edit_title']) && isset($_POST['edit_content']) && $_SESSION['user_id']) {
    $note_id = $_POST['edit_note_id'];  // 获取编辑的笔记 ID
    $new_title = $_POST['edit_title'];  // 获取新的标题
    $new_content = $_POST['edit_content'];  // 获取新的内容

    // 去除内容中的多余换行符
    $new_content = trim($new_content);

    // 对用户输入进行转义,防止 XSS 攻击
    $new_title = htmlspecialchars($new_title, ENT_QUOTES, 'UTF-8');
    $new_content = htmlspecialchars($new_content, ENT_QUOTES, 'UTF-8');

    // 更新数据库中的笔记数据
    $sql = "UPDATE notes SET title = ?, content = ? WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssii", $new_title, $new_content, $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 修改成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记更新成功!'); window.location.href='';</script>";
    } else {
        // 更新失败,输出错误信息
        echo "<script>alert('更新失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 删除笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_note_id']) && $_SESSION['user_id']) {
    $note_id = $_POST['delete_note_id'];  // 获取要删除的笔记 ID
    $sql = "DELETE FROM notes WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 删除成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记删除成功!');</script>";
    } else {
        // 删除失败,输出错误信息
        echo "<script>alert('删除失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 用户登出
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['logout'])) {
    session_destroy();  // 销毁会话
    $_SESSION['user_id'] = null;  // 清空会话中的 user_id
    // echo "<script>alert('您已成功登出!'); window.location.href='';</script>";
}

// 获取当前用户的所有笔记
if ($_SESSION['user_id']) {
    $sql = "SELECT * FROM notes WHERE user_id = ? ORDER BY created_at DESC";  // 按创建时间倒序获取当前用户的所有笔记
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();  // 获取查询结果
} else {
    $result = null;  // 如果没有登录,设置结果为 null
}

// 处理笔记中的链接
function parseLinks($content) {
    $pattern = "/(https?:\/\/[^\s]+)/i";  // 匹配 URL 的正则表达式
    $replacement = '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>';  // 将匹配到的 URL 替换为可点击的链接
    return preg_replace($pattern, $replacement, $content);
}

// 处理笔记内容中的换行符
function processNoteContent($content) {
    // 去除多余的换行符
    $content = preg_replace('/\n+/', "\n", $content);
    // 将换行符转换为 <br> 标签,适合 HTML 展示
    return nl2br($content);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记事本</title>
    <style>
        /* 基本样式 */
        body { 
            font-family: Arial, sans-serif; /* 设置字体 */
            padding: 20px; /* 添加内边距 */
        }

        textarea { 
            width: 100%; /* 设置文本框宽度 */
            height: 200px; /* 设置文本框高度 */
        }

        .note { 
            margin-bottom: 20px; /* 设置笔记底部间距 */
            padding: 15px; /* 设置内边距 */
            border: 1px solid #ddd; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
            background-color: #f9f9f9; /* 设置背景颜色 */
        }

        .note h3 { 
            margin: 0; /* 去掉标题的外边距 */
            font-size: 20px; /* 设置标题字体大小 */
        }

        .note p { 
            margin: 10px 0; /* 设置段落的上下间距 */
            font-size: 16px; /* 设置段落字体大小 */
            color: #333; /* 设置段落文字颜色 */
            white-space: pre-wrap; /* 保留空格并换行 */
        }

        .note small { 
            display: block; /* 使小字独占一行 */
            margin-top: 10px; /* 设置顶部间距 */
            font-size: 12px; /* 设置字体大小 */
            color: #888; /* 设置文字颜色 */
        }

        /* 按钮样式 */
        button {
            border: none; /* 去掉按钮边框 */
            padding: 5px 10px; /* 设置内边距 */
            cursor: pointer; /* 设置鼠标悬停时为手指形状 */
            border-radius: 5px; /* 设置圆角边框 */
            transition: background-color 0.3s ease; /* 设置背景色过渡效果 */
        }

        /* 删除按钮样式 */
        .delete-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .delete-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 复制按钮样式 */
        .copy-btn { 
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .copy-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 编辑按钮样式 */
        .edit-btn {
            background-color: #2196F3; /* 设置按钮背景色为蓝色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .edit-btn:hover {
            background-color: #1976D2; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 登出按钮样式 */
        .logout-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
            margin-top: 20px; /* 设置顶部间距 */
        }

        .logout-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 表单容器样式 */
        .form-container { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使元素垂直排列 */
            align-items: center; /* 水平居中对齐 */
            margin-bottom: 20px; /* 设置底部间距 */
        }

        .form-container form { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使表单元素垂直排列 */
            width: 100%; /* 设置宽度为100% */
            max-width: 300px; /* 最大宽度为300px */
        }

        .form-container input, 
        .form-container textarea, 
        .form-container button { 
            margin-bottom: 10px; /* 设置元素之间的间距 */
        }

        .form-container input, 
        .form-container textarea { 
            padding: 10px; /* 设置内边距 */
            border: 1px solid #ccc; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
        }

        .form-container button { 
            padding: 10px; /* 设置内边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
        }

        .form-container button:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮样式 */
        .scroll-btn { 
            position: fixed; /* 固定按钮位置 */
            right: 20px; /* 设置右边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            padding: 10px; /* 设置内边距 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
            font-size: 16px; /* 设置字体大小 */
            z-index: 9999; /* 设置按钮层级 */
        }

        .scroll-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮位置 */
        .scroll-btn-bottom { 
            bottom: 20px; /* 设置按钮距离底部20px */
        }

        .scroll-btn-top { 
            bottom: 70px; /* 设置按钮距离底部70px */
        }

    </style>
</head>
<body>
    
<!-- 记事本内容 -->
</body>
</html>

    <h1>记事本</h1>

<?php if (!isset($_SESSION['user_id'])): ?>
    <div class="form-container">
        <h2>登录 / 注册</h2>
        <form method="POST" onsubmit="return validateForm()">
            <input type="text" name="username" placeholder="用户名" required autocomplete="off">
            <input type="password" name="password" placeholder="密码" required autocomplete="off">
            <button type="submit" name="login">登录</button>
            <button type="submit" name="register">注册</button>
        </form>
    </div>
<?php else: ?>
    <form method="POST">
        <!-- 去掉 required 属性 -->
        <input type="text" name="title" placeholder="标题" maxlength="100"><br><br> 
        <textarea name="content" placeholder="写下你的笔记..." required></textarea><br><br>
        <button type="submit" name="save_note">保存笔记</button>
    </form>

    <h2>所有笔记</h2>
    <?php if ($result && $result->num_rows > 0): ?>
        <?php while($row = $result->fetch_assoc()): ?>
            <div class='note' id='note_<?php echo $row['id']; ?>'>
                <h3><?php echo htmlspecialchars($row['title'] ?: '无标题'); ?></h3>
                <?php
                    // 处理笔记内容,去除多余的换行符并正确渲染链接
                    $content_with_links = parseLinks($row['content']);
                    $processed_content = processNoteContent($content_with_links);
                    echo "<p>" . $processed_content . "</p>";
                ?>
                <small>创建时间: <?php echo $row['created_at']; ?></small>
                <form method='POST' style='display:inline;' onsubmit="return confirm('确定要删除这篇笔记吗?');">
                    <input type='hidden' name='delete_note_id' value='<?php echo $row['id']; ?>'>
                    <button type='submit' class='delete-btn'>删除</button>
                </form>
                <button class='copy-btn' onclick='copyNoteContent(<?php echo $row['id']; ?>)'>复制</button>
                <button class="edit-btn" onclick="editNote(<?php echo $row['id']; ?>)">编辑</button>
            </div>
        <?php endwhile; ?>
    <?php else: ?>
        <p>没有笔记记录。</p>
    <?php endif; ?>
<?php endif; ?>

<?php if ($_SESSION['user_id']): ?>
    <form method="POST" style="display: flex; justify-content: center; width: 100%;">
        <button type="submit" name="logout" class="logout-btn">登出</button>
    </form>
<?php endif; ?>


<!-- 滚动按钮 -->
<button class="scroll-btn scroll-btn-top" onclick="scrollToPosition('top')">顶部</button>
<button class="scroll-btn scroll-btn-bottom" onclick="scrollToPosition('bottom')">底部</button>

<script>
    // 页面滚动到指定位置
    function scrollToPosition(position) {
        if (position === 'top') {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (position === 'bottom') {
            window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
        }
    }

    // 复制笔记内容到剪贴板
    function copyNoteContent(noteId) {
        var noteContent = document.getElementById('note_' + noteId).querySelector('p').innerText;
        var textArea = document.createElement('textarea');
        textArea.value = noteContent;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
    }

    // 编辑笔记功能
    function editNote(noteId) {
        var noteDiv = document.getElementById('note_' + noteId);
        var title = noteDiv.querySelector('h3').innerText;
        var content = noteDiv.querySelector('p').innerText;

        var newTitle = prompt("编辑标题:", title);
        var newContent = prompt("编辑内容:", content);

        if (newTitle && newContent) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '';

            var noteIdInput = document.createElement('input');
            noteIdInput.type = 'hidden';
            noteIdInput.name = 'edit_note_id';
            noteIdInput.value = noteId;
            form.appendChild(noteIdInput);

            var titleInput = document.createElement('input');
            titleInput.type = 'hidden';
            titleInput.name = 'edit_title';
            titleInput.value = newTitle;
            form.appendChild(titleInput);

            var contentInput = document.createElement('textarea');
            contentInput.name = 'edit_content';
            contentInput.value = newContent;
            form.appendChild(contentInput);

            document.body.appendChild(form);
            form.submit();
        }
    }

    // 表单验证:确保输入框不为空
    function validateForm() {
        const username = document.querySelector('input[name="username"]').value;
        const password = document.querySelector('input[name="password"]').value;
        if (username === "" || password === "") {
            alert("用户名和密码不能为空");
            return false;
        }
        return true;
    }
    
</script>

</body>
</html>

1.1 失败后的补救罢了

<?php
// 数据库连接配置
$servername = "localhost";  // 数据库主机
$username = "notebook";     // 数据库用户名
$password = "eYbFYJSHpHP2HRXw"; // 数据库密码
$dbname = "notebook";       // 数据库名称

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查数据库连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);  // 连接失败则输出错误信息并终止脚本执行
}

// 启动会话
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = null;  // 未登录则将 user_id 设置为 null
}

// 用户注册处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    $username = $_POST['username'];  // 获取用户输入的用户名
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // 对密码进行哈希处理

    // 检查用户名是否已存在
    $check_sql = "SELECT COUNT(*) FROM users WHERE username = ?";  // 检查用户名是否已存在
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("s", $username);
    $check_stmt->execute();
    $check_stmt->bind_result($count);  // 获取查询结果
    $check_stmt->fetch();
    $check_stmt->close();

    if ($count > 0) {
        // 用户名已存在,提示用户
        echo "<script>alert('用户名已存在,请使用其他用户名!');</script>";
    } else {
        // 用户名不存在,可以注册
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";  // 插入新用户数据
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $username, $password);
        if ($stmt->execute()) {
            // 注册成功,提示用户登录
            echo "<script>alert('注册成功,请登录!');</script>";
        } else {
            // 注册失败,显示错误信息
            echo "<script>alert('注册失败:" . $stmt->error . "');</script>";
        }
        $stmt->close();
    }
}

// 用户登录处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) {
    $username = $_POST['username'];  // 获取用户名
    $password = $_POST['password'];  // 获取密码

    // 查询用户名对应的用户数据
    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // 用户存在,验证密码
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];  // 登录成功,将用户 ID 存入会话
            // echo "<script>alert('登录成功!');</script>";
        } else {
            // 密码错误
            echo "<script>alert('密码错误!');</script>";
        }
    } else {
        // 用户不存在
        echo "<script>alert('用户不存在!');</script>";
    }
    $stmt->close();
}

// 保存笔记处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_note']) && $_SESSION['user_id']) {
    // 获取标题,如果没有标题则为 null
    $title = isset($_POST['title']) && !empty($_POST['title']) ? $_POST['title'] : null;
    $content = $_POST['content'];  // 获取笔记内容
    $user_id = $_SESSION['user_id'];  // 获取当前用户 ID

    // 去除多余的换行符
    $content = trim($content);

    // 转义用户输入,防止 XSS 攻击
    $title = $title !== null ? htmlspecialchars($title, ENT_QUOTES, 'UTF-8') : ''; 
    $content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

    // 插入笔记数据
    $sql = "INSERT INTO notes (user_id, title, content) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iss", $user_id, $title, $content);
    if ($stmt->execute()) {
        // 保存成功
        // 可以根据需要返回成功提示
    } else {
        // 保存失败,显示错误信息
        echo "<script>alert('保存失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 编辑笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_note_id']) && isset($_POST['edit_title']) && isset($_POST['edit_content']) && $_SESSION['user_id']) {
    $note_id = $_POST['edit_note_id'];  // 获取编辑的笔记 ID
    $new_title = $_POST['edit_title'];  // 获取新的标题
    $new_content = $_POST['edit_content'];  // 获取新的内容

    // 去除内容中的多余换行符
    $new_content = trim($new_content);

    // 对用户输入进行转义,防止 XSS 攻击
    $new_title = htmlspecialchars($new_title, ENT_QUOTES, 'UTF-8');
    $new_content = htmlspecialchars($new_content, ENT_QUOTES, 'UTF-8');

    // 更新数据库中的笔记数据
    $sql = "UPDATE notes SET title = ?, content = ? WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssii", $new_title, $new_content, $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 修改成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记更新成功!'); window.location.href='';</script>";
    } else {
        // 更新失败,输出错误信息
        echo "<script>alert('更新失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 删除笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_note_id']) && $_SESSION['user_id']) {
    $note_id = $_POST['delete_note_id'];  // 获取要删除的笔记 ID
    $sql = "DELETE FROM notes WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 删除成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记删除成功!');</script>";
    } else {
        // 删除失败,输出错误信息
        echo "<script>alert('删除失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 用户登出
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['logout'])) {
    session_destroy();  // 销毁会话
    $_SESSION['user_id'] = null;  // 清空会话中的 user_id
    // echo "<script>alert('您已成功登出!'); window.location.href='';</script>";
}

// 获取当前用户的所有笔记
if ($_SESSION['user_id']) {
    $sql = "SELECT * FROM notes WHERE user_id = ? ORDER BY created_at DESC";  // 按创建时间倒序获取当前用户的所有笔记
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();  // 获取查询结果
} else {
    $result = null;  // 如果没有登录,设置结果为 null
}

// 处理笔记中的链接
function parseLinks($content) {
    $pattern = "/(https?:\/\/[^\s]+)/i";  // 匹配 URL 的正则表达式
    $replacement = '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>';  // 将匹配到的 URL 替换为可点击的链接
    return preg_replace($pattern, $replacement, $content);
}

// 处理笔记内容中的换行符
function processNoteContent($content) {
    // 将换行符转换为 <br> 标签,适合 HTML 展示
    return nl2br($content);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记事本</title>
    <style>
        /* 基本样式 */
        body { 
            font-family: Arial, sans-serif; /* 设置字体 */
            padding: 20px; /* 添加内边距 */
        }

        textarea { 
            width: 100%; /* 设置文本框宽度 */
            height: 200px; /* 设置文本框高度 */
        }

        .note { 
            margin-bottom: 20px; /* 设置笔记底部间距 */
            padding: 15px; /* 设置内边距 */
            border: 1px solid #ddd; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
            background-color: #f9f9f9; /* 设置背景颜色 */
        }

        .note h3 { 
            margin: 0; /* 去掉标题的外边距 */
            font-size: 20px; /* 设置标题字体大小 */
        }

        .note p { 
            margin: 10px 0; /* 设置段落的上下间距 */
            font-size: 16px; /* 设置段落字体大小 */
            color: #333; /* 设置段落文字颜色 */
            white-space: pre-wrap; /* 保留空格并换行 */
        }

        .note small { 
            display: block; /* 使小字独占一行 */
            margin-top: 10px; /* 设置顶部间距 */
            font-size: 12px; /* 设置字体大小 */
            color: #888; /* 设置文字颜色 */
        }

        /* 按钮样式 */
        button {
            border: none; /* 去掉按钮边框 */
            padding: 5px 10px; /* 设置内边距 */
            cursor: pointer; /* 设置鼠标悬停时为手指形状 */
            border-radius: 5px; /* 设置圆角边框 */
            transition: background-color 0.3s ease; /* 设置背景色过渡效果 */
        }

        /* 删除按钮样式 */
        .delete-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .delete-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 复制按钮样式 */
        .copy-btn { 
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .copy-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 编辑按钮样式 */
        .edit-btn {
            background-color: #2196F3; /* 设置按钮背景色为蓝色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .edit-btn:hover {
            background-color: #1976D2; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 登出按钮样式 */
        .logout-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
            margin-top: 20px; /* 设置顶部间距 */
        }

        .logout-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 表单容器样式 */
        .form-container { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使元素垂直排列 */
            align-items: center; /* 水平居中对齐 */
            margin-bottom: 20px; /* 设置底部间距 */
        }

        .form-container form { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使表单元素垂直排列 */
            width: 100%; /* 设置宽度为100% */
            max-width: 300px; /* 最大宽度为300px */
        }

        .form-container input, 
        .form-container textarea, 
        .form-container button { 
            margin-bottom: 10px; /* 设置元素之间的间距 */
        }

        .form-container input, 
        .form-container textarea { 
            padding: 10px; /* 设置内边距 */
            border: 1px solid #ccc; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
        }

        .form-container button { 
            padding: 10px; /* 设置内边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
        }

        .form-container button:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮样式 */
        .scroll-btn { 
            position: fixed; /* 固定按钮位置 */
            right: 20px; /* 设置右边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            padding: 10px; /* 设置内边距 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
            font-size: 16px; /* 设置字体大小 */
            z-index: 9999; /* 设置按钮层级 */
        }

        .scroll-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮位置 */
        .scroll-btn-bottom { 
            bottom: 20px; /* 设置按钮距离底部20px */
        }

        .scroll-btn-top { 
            bottom: 70px; /* 设置按钮距离底部70px */
        }

    </style>
</head>
<body>
    
<!-- 记事本内容 -->
</body>
</html>

    <h1>记事本</h1>

<?php if (!isset($_SESSION['user_id'])): ?>
    <div class="form-container">
        <h2>登录 / 注册</h2>
        <form method="POST" onsubmit="return validateForm()">
            <input type="text" name="username" placeholder="用户名" required autocomplete="off">
            <input type="password" name="password" placeholder="密码" required autocomplete="off">
            <button type="submit" name="login">登录</button>
            <button type="submit" name="register">注册</button>
        </form>
    </div>
<?php else: ?>
    <form method="POST">
        <!-- 去掉 required 属性 -->
        <input type="text" name="title" placeholder="标题" maxlength="100"><br><br> 
        <textarea name="content" placeholder="写下你的笔记..." required></textarea><br><br>
        <button type="submit" name="save_note">保存笔记</button>
    </form>

    <h2>所有笔记</h2>
    <?php if ($result && $result->num_rows > 0): ?>
        <?php while($row = $result->fetch_assoc()): ?>
            <div class='note' id='note_<?php echo $row['id']; ?>'>
                <h3><?php echo htmlspecialchars($row['title'] ?: '无标题'); ?></h3>
                <?php
                    // 处理笔记内容,去除多余的换行符并正确渲染链接
                    $content_with_links = parseLinks($row['content']);
                    $processed_content = processNoteContent($content_with_links);
                    echo "<p>" . $processed_content . "</p>";
                ?>
                <small>创建时间: <?php echo $row['created_at']; ?></small>
                <form method='POST' style='display:inline;' onsubmit="return confirm('确定要删除这篇笔记吗?');">
                    <input type='hidden' name='delete_note_id' value='<?php echo $row['id']; ?>'>
                    <button type='submit' class='delete-btn'>删除</button>
                </form>
                <button class='copy-btn' onclick='copyNoteContent(<?php echo $row['id']; ?>)'>复制</button>
                <button class="edit-btn" onclick="editNote(<?php echo $row['id']; ?>)">编辑</button>
            </div>
        <?php endwhile; ?>
    <?php else: ?>
        <p>没有笔记记录。</p>
    <?php endif; ?>
<?php endif; ?>

<?php if ($_SESSION['user_id']): ?>
    <form method="POST" style="display: flex; justify-content: center; width: 100%;">
        <button type="submit" name="logout" class="logout-btn">登出</button>
    </form>
<?php endif; ?>


<!-- 滚动按钮 -->
<button class="scroll-btn scroll-btn-top" onclick="scrollToPosition('top')">顶部</button>
<button class="scroll-btn scroll-btn-bottom" onclick="scrollToPosition('bottom')">底部</button>

<script>
    // 页面滚动到指定位置
    function scrollToPosition(position) {
        if (position === 'top') {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (position === 'bottom') {
            window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
        }
    }

    // 复制笔记内容到剪贴板
    function copyNoteContent(noteId) {
        var noteContent = document.getElementById('note_' + noteId).querySelector('p').innerText;
        var textArea = document.createElement('textarea');
        textArea.value = noteContent;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
    }

    // 编辑笔记功能
    function editNote(noteId) {
        var noteDiv = document.getElementById('note_' + noteId);
        var title = noteDiv.querySelector('h3').innerText;
        var content = noteDiv.querySelector('p').innerText;

        var newTitle = prompt("编辑标题:", title);
        var newContent = prompt("编辑内容:", content);

        if (newTitle && newContent) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '';

            var noteIdInput = document.createElement('input');
            noteIdInput.type = 'hidden';
            noteIdInput.name = 'edit_note_id';
            noteIdInput.value = noteId;
            form.appendChild(noteIdInput);

            var titleInput = document.createElement('input');
            titleInput.type = 'hidden';
            titleInput.name = 'edit_title';
            titleInput.value = newTitle;
            form.appendChild(titleInput);

            var contentInput = document.createElement('textarea');
            contentInput.name = 'edit_content';
            contentInput.value = newContent;
            form.appendChild(contentInput);

            document.body.appendChild(form);
            form.submit();
        }
    }

    // 表单验证:确保输入框不为空
    function validateForm() {
        const username = document.querySelector('input[name="username"]').value;
        const password = document.querySelector('input[name="password"]').value;
        if (username === "" || password === "") {
            alert("用户名和密码不能为空");
            return false;
        }
        return true;
    }
    
    // 移除处理上移的 JavaScript 代码
    // function moveNoteUp(noteId) {
    //     var form = document.createElement('form');
    //     form.method = 'POST';
    //     form.action = '';

    //     var noteIdInput = document.createElement('input');
    //     noteIdInput.type = 'hidden';
    //     noteIdInput.name = 'move_up_note_id';
    //     noteIdInput.value = noteId;
    //     form.appendChild(noteIdInput);

    //     document.body.appendChild(form);
    //     form.submit();
    // }

    // 移除处理下移的 JavaScript 代码
    // function moveNoteDown(noteId) {
    //     var form = document.createElement('form');
    //     form.method = 'POST';
    //     form.action = '';

    //     var noteIdInput = document.createElement('input');
    //     noteIdInput.type = 'hidden';
    //     noteIdInput.name = 'move_down_note_id';
    //     noteIdInput.value = noteId;
    //     form.appendChild(noteIdInput);

    //     document.body.appendChild(form);
    //     form.submit();
    // }
</script>

</body>
</html>

1.2

<?php
// 数据库连接配置
$servername = "localhost";  // 数据库主机
$username = "notebook";     // 数据库用户名
$password = "eYbFYJSHpHP2HRXw"; // 数据库密码
$dbname = "notebook";       // 数据库名称

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查数据库连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);  // 连接失败则输出错误信息并终止脚本执行
}

// 更新访问计数器
$update_sql = "UPDATE visits SET count = count + 1 WHERE id = 1";
$conn->query($update_sql);

// 获取当前访问计数
$select_sql = "SELECT count FROM visits WHERE id = 1";
$result = $conn->query($select_sql);
$visit_count = 0;
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $visit_count = $row['count'];
} else {
    // 如果表中没有记录,则插入一条初始记录
    $insert_sql = "INSERT INTO visits (count) VALUES (1)";
    $conn->query($insert_sql);
    $visit_count = 1;
}

// 启动会话
session_start();

// 检查用户是否已登录
if (!isset($_SESSION['user_id'])) {
    $_SESSION['user_id'] = null;  // 未登录则将 user_id 设置为 null
}

// 用户注册处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['register'])) {
    $username = $_POST['username'];  // 获取用户输入的用户名
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT); // 对密码进行哈希处理

    // 检查用户名是否已存在
    $check_sql = "SELECT COUNT(*) FROM users WHERE username = ?";  // 检查用户名是否已存在
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("s", $username);
    $check_stmt->execute();
    $check_stmt->bind_result($count);  // 获取查询结果
    $check_stmt->fetch();
    $check_stmt->close();

    if ($count > 0) {
        // 用户名已存在,提示用户
        echo "<script>alert('用户名已存在,请使用其他用户名!');</script>";
    } else {
        // 用户名不存在,可以注册
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";  // 插入新用户数据
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("ss", $username, $password);
        if ($stmt->execute()) {
            // 注册成功,提示用户登录
            echo "<script>alert('注册成功,请登录!');</script>";
        } else {
            // 注册失败,显示错误信息
            echo "<script>alert('注册失败:" . $stmt->error . "');</script>";
        }
        $stmt->close();
    }
}

// 用户登录处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['login'])) {
    $username = $_POST['username'];  // 获取用户名
    $password = $_POST['password'];  // 获取密码

    // 查询用户名对应的用户数据
    $sql = "SELECT * FROM users WHERE username = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        // 用户存在,验证密码
        $user = $result->fetch_assoc();
        if (password_verify($password, $user['password'])) {
            $_SESSION['user_id'] = $user['id'];  // 登录成功,将用户 ID 存入会话
            // echo "<script>alert('登录成功!');</script>";
        } else {
            // 密码错误
            echo "<script>alert('密码错误!');</script>";
        }
    } else {
        // 用户不存在
        echo "<script>alert('用户不存在!');</script>";
    }
    $stmt->close();
}

// 保存笔记处理
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_note']) && $_SESSION['user_id']) {
    // 获取标题,如果没有标题则为 null
    $title = isset($_POST['title']) && !empty($_POST['title']) ? $_POST['title'] : null;
    $content = $_POST['content'];  // 获取笔记内容
    $user_id = $_SESSION['user_id'];  // 获取当前用户 ID

    // 去除多余的换行符
    $content = trim($content);

    // 转义用户输入,防止 XSS 攻击
    $title = $title !== null ? htmlspecialchars($title, ENT_QUOTES, 'UTF-8') : ''; 
    $content = htmlspecialchars($content, ENT_QUOTES, 'UTF-8');

    // 插入笔记数据
    $sql = "INSERT INTO notes (user_id, title, content) VALUES (?, ?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("iss", $user_id, $title, $content);
    if ($stmt->execute()) {
        // 保存成功
        // 可以根据需要返回成功提示
    } else {
        // 保存失败,显示错误信息
        echo "<script>alert('保存失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 编辑笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_note_id']) && isset($_POST['edit_title']) && isset($_POST['edit_content']) && $_SESSION['user_id']) {
    $note_id = $_POST['edit_note_id'];  // 获取编辑的笔记 ID
    $new_title = $_POST['edit_title'];  // 获取新的标题
    $new_content = $_POST['edit_content'];  // 获取新的内容

    // 去除内容中的多余换行符
    $new_content = trim($new_content);

    // 对用户输入进行转义,防止 XSS 攻击
    $new_title = htmlspecialchars($new_title, ENT_QUOTES, 'UTF-8');
    $new_content = htmlspecialchars($new_content, ENT_QUOTES, 'UTF-8');

    // 更新数据库中的笔记数据
    $sql = "UPDATE notes SET title = ?, content = ? WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssii", $new_title, $new_content, $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 修改成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记更新成功!'); window.location.href='';</script>";
    } else {
        // 更新失败,输出错误信息
        echo "<script>alert('更新失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 删除笔记
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['delete_note_id']) && $_SESSION['user_id']) {
    $note_id = $_POST['delete_note_id'];  // 获取要删除的笔记 ID
    $sql = "DELETE FROM notes WHERE id = ? AND user_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ii", $note_id, $_SESSION['user_id']);
    if ($stmt->execute()) {
        // 删除成功后,可以在此处添加跳转或提示
        // echo "<script>alert('笔记删除成功!');</script>";
    } else {
        // 删除失败,输出错误信息
        echo "<script>alert('删除失败:" . $stmt->error . "');</script>";
    }
    $stmt->close();
}

// 用户登出
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['logout'])) {
    session_destroy();  // 销毁会话
    $_SESSION['user_id'] = null;  // 清空会话中的 user_id
    // echo "<script>alert('您已成功登出!'); window.location.href='';</script>";
}

// 获取当前用户的所有笔记
if ($_SESSION['user_id']) {
    $sql = "SELECT * FROM notes WHERE user_id = ? ORDER BY created_at DESC";  // 按创建时间倒序获取当前用户的所有笔记
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $_SESSION['user_id']);
    $stmt->execute();
    $result = $stmt->get_result();  // 获取查询结果
} else {
    $result = null;  // 如果没有登录,设置结果为 null
}

// 处理笔记中的链接
function parseLinks($content) {
    $pattern = "/(https?:\/\/[^\s]+)/i";  // 匹配 URL 的正则表达式
    $replacement = '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>';  // 将匹配到的 URL 替换为可点击的链接
    return preg_replace($pattern, $replacement, $content);
}

// 处理笔记内容中的换行符
function processNoteContent($content) {
    // 将换行符转换为 <br> 标签,适合 HTML 展示
    return nl2br($content);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记事本</title>
    <style>
        /* 基本样式 */
        body { 
            font-family: Arial, sans-serif; /* 设置字体 */
            padding: 20px; /* 添加内边距 */
        }

        textarea { 
            width: 100%; /* 设置文本框宽度 */
            height: 200px; /* 设置文本框高度 */
        }

        .note { 
            margin-bottom: 20px; /* 设置笔记底部间距 */
            padding: 15px; /* 设置内边距 */
            border: 1px solid #ddd; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
            background-color: #f9f9f9; /* 设置背景颜色 */
        }

        .note h3 { 
            margin: 0; /* 去掉标题的外边距 */
            font-size: 20px; /* 设置标题字体大小 */
        }

        .note p { 
            margin: 10px 0; /* 设置段落的上下间距 */
            font-size: 16px; /* 设置段落字体大小 */
            color: #333; /* 设置段落文字颜色 */
            white-space: pre-wrap; /* 保留空格并换行 */
        }

        .note small { 
            display: block; /* 使小字独占一行 */
            margin-top: 10px; /* 设置顶部间距 */
            font-size: 12px; /* 设置字体大小 */
            color: #888; /* 设置文字颜色 */
        }

        /* 按钮样式 */
        button {
            border: none; /* 去掉按钮边框 */
            padding: 5px 10px; /* 设置内边距 */
            cursor: pointer; /* 设置鼠标悬停时为手指形状 */
            border-radius: 5px; /* 设置圆角边框 */
            transition: background-color 0.3s ease; /* 设置背景色过渡效果 */
        }

        /* 删除按钮样式 */
        .delete-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .delete-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 复制按钮样式 */
        .copy-btn { 
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .copy-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 编辑按钮样式 */
        .edit-btn {
            background-color: #2196F3; /* 设置按钮背景色为蓝色 */
            color: white; /* 设置文字颜色为白色 */
        }

        .edit-btn:hover {
            background-color: #1976D2; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 登出按钮样式 */
        .logout-btn { 
            background-color: #f44336; /* 设置按钮背景色为红色 */
            color: white; /* 设置文字颜色为白色 */
            margin-top: 20px; /* 设置顶部间距 */
        }

        .logout-btn:hover { 
            background-color: #d32f2f; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 表单容器样式 */
        .form-container { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使元素垂直排列 */
            align-items: center; /* 水平居中对齐 */
            margin-bottom: 20px; /* 设置底部间距 */
        }

        .form-container form { 
            display: flex; /* 使用flex布局 */
            flex-direction: column; /* 使表单元素垂直排列 */
            width: 100%; /* 设置宽度为100% */
            max-width: 300px; /* 最大宽度为300px */
        }

        .form-container input, 
        .form-container textarea, 
        .form-container button { 
            margin-bottom: 10px; /* 设置元素之间的间距 */
        }

        .form-container input, 
        .form-container textarea { 
            padding: 10px; /* 设置内边距 */
            border: 1px solid #ccc; /* 设置边框 */
            border-radius: 5px; /* 设置圆角边框 */
        }

        .form-container button { 
            padding: 10px; /* 设置内边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
        }

        .form-container button:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮样式 */
        .scroll-btn { 
            position: fixed; /* 固定按钮位置 */
            right: 20px; /* 设置右边距 */
            background-color: #4CAF50; /* 设置按钮背景色为绿色 */
            color: white; /* 设置文字颜色为白色 */
            border: none; /* 去掉按钮边框 */
            padding: 10px; /* 设置内边距 */
            border-radius: 5px; /* 设置圆角边框 */
            cursor: pointer; /* 鼠标悬停时为手指形状 */
            font-size: 16px; /* 设置字体大小 */
            z-index: 9999; /* 设置按钮层级 */
        }

        .scroll-btn:hover { 
            background-color: #388E3C; /* 鼠标悬停时按钮颜色变深 */
        }

        /* 滚动按钮位置 */
        .scroll-btn-bottom { 
            bottom: 20px; /* 设置按钮距离底部20px */
        }

        .scroll-btn-top { 
            bottom: 70px; /* 设置按钮距离底部70px */
        }

    </style>
</head>
<body>
    <h1>记事本</h1>
    <p>访问次数: <?php echo $visit_count; ?></p>

<?php if (!isset($_SESSION['user_id'])): ?>
    <div class="form-container">
        <h2>登录 / 注册</h2>
        <form method="POST" onsubmit="return validateForm()">
            <input type="text" name="username" placeholder="用户名" required autocomplete="off">
            <input type="password" name="password" placeholder="密码" required autocomplete="off">
            <button type="submit" name="login">登录</button>
            <button type="submit" name="register">注册</button>
        </form>
    </div>
<?php else: ?>
    <form method="POST">
        <!-- 去掉 required 属性 -->
        <input type="text" name="title" placeholder="标题" maxlength="100"><br><br> 
        <textarea name="content" placeholder="写下你的笔记..." required></textarea><br><br>
        <button type="submit" name="save_note">保存笔记</button>
    </form>

    <h2>所有笔记</h2>
    <?php if ($result && $result->num_rows > 0): ?>
        <?php while($row = $result->fetch_assoc()): ?>
            <div class='note' id='note_<?php echo $row['id']; ?>'>
                <h3><?php echo htmlspecialchars($row['title'] ?: '无标题'); ?></h3>
                <?php
                    // 处理笔记内容,去除多余的换行符并正确渲染链接
                    $content_with_links = parseLinks($row['content']);
                    $processed_content = processNoteContent($content_with_links);
                    echo "<p>" . $processed_content . "</p>";
                ?>
                <small>创建时间: <?php echo $row['created_at']; ?></small>
                <form method='POST' style='display:inline;' onsubmit="return confirm('确定要删除这篇笔记吗?');">
                    <input type='hidden' name='delete_note_id' value='<?php echo $row['id']; ?>'>
                    <button type='submit' class='delete-btn'>删除</button>
                </form>
                <button class='copy-btn' onclick='copyNoteContent(<?php echo $row['id']; ?>)'>复制</button>
                <button class="edit-btn" onclick="editNote(<?php echo $row['id']; ?>)">编辑</button>
            </div>
        <?php endwhile; ?>
    <?php else: ?>
        <p>没有笔记记录。</p>
    <?php endif; ?>
<?php endif; ?>

<?php if ($_SESSION['user_id']): ?>
    <form method="POST" style="display: flex; justify-content: center; width: 100%;">
        <button type="submit" name="logout" class="logout-btn">登出</button>
    </form>
<?php endif; ?>


<!-- 滚动按钮 -->
<button class="scroll-btn scroll-btn-top" onclick="scrollToPosition('top')">顶部</button>
<button class="scroll-btn scroll-btn-bottom" onclick="scrollToPosition('bottom')">底部</button>

<script>
    // 页面滚动到指定位置
    function scrollToPosition(position) {
        if (position === 'top') {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (position === 'bottom') {
            window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
        }
    }

    // 复制笔记内容到剪贴板
    function copyNoteContent(noteId) {
        var noteContent = document.getElementById('note_' + noteId).querySelector('p').innerText;
        var textArea = document.createElement('textarea');
        textArea.value = noteContent;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
    }

    // 编辑笔记功能
    function editNote(noteId) {
        var noteDiv = document.getElementById('note_' + noteId);
        var title = noteDiv.querySelector('h3').innerText;
        var content = noteDiv.querySelector('p').innerText;

        var newTitle = prompt("编辑标题:", title);
        var newContent = prompt("编辑内容:", content);

        if (newTitle && newContent) {
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = '';

            var noteIdInput = document.createElement('input');
            noteIdInput.type = 'hidden';
            noteIdInput.name = 'edit_note_id';
            noteIdInput.value = noteId;
            form.appendChild(noteIdInput);

            var titleInput = document.createElement('input');
            titleInput.type = 'hidden';
            titleInput.name = 'edit_title';
            titleInput.value = newTitle;
            form.appendChild(titleInput);

            var contentInput = document.createElement('textarea');
            contentInput.name = 'edit_content';
            contentInput.value = newContent;
            form.appendChild(contentInput);

            document.body.appendChild(form);
            form.submit();
        }
    }

    // 表单验证:确保输入框不为空
    function validateForm() {
        const username = document.querySelector('input[name="username"]').value;
        const password = document.querySelector('input[name="password"]').value;
        if (username === "" || password === "") {
            alert("用户名和密码不能为空");
            return false;
        }
        return true;
    }
    
    // 移除处理上移的 JavaScript 代码
    // function moveNoteUp(noteId) {
    //     var form = document.createElement('form');
    //     form.method = 'POST';
    //     form.action = '';

    //     var noteIdInput = document.createElement('input');
    //     noteIdInput.type = 'hidden';
    //     noteIdInput.name = 'move_up_note_id';
    //     noteIdInput.value = noteId;
    //     form.appendChild(noteIdInput);

    //     document.body.appendChild(form);
    //     form.submit();
    // }

    // 移除处理下移的 JavaScript 代码
    // function moveNoteDown(noteId) {
    //     var form = document.createElement('form');
    //     form.method = 'POST';
    //     form.action = '';

    //     var noteIdInput = document.createElement('input');
    //     noteIdInput.type = 'hidden';
    //     noteIdInput.name = 'move_down_note_id';
    //     noteIdInput.value = noteId;
    //     form.appendChild(noteIdInput);

    //     document.body.appendChild(form);
    //     form.submit();
    // }
</script>

</body>
</html>

感谢观看服务器玩法系列(4)——搭建记事本(原创),欢迎分享https://cn-lcx.cn/2025/01/28/__trashed-7__trashed/
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇