處理todo數據的一種常見方法是使用數據庫來存儲和管理todo列表。以下是一個簡單的示例,演示如何在PHP中有效地處理todo數據:
todos
的表:CREATE TABLE todos (
id INT AUTO_INCREMENT PRIMARY KEY,
task VARCHAR(255) NOT NULL,
completed BOOLEAN NOT NULL DEFAULT false
);
<?php
// 連接到數據庫
$pdo = new PDO('mysql:host=localhost;dbname=your_database_name', 'username', 'password');
// 添加一個todo任務
if ($_POST['action'] == 'add_todo') {
$task = $_POST['task'];
$stmt = $pdo->prepare('INSERT INTO todos (task) VALUES (:task)');
$stmt->execute(['task' => $task]);
}
// 更新todo任務的完成狀態
if ($_POST['action'] == 'update_todo') {
$id = $_POST['id'];
$completed = $_POST['completed'];
$stmt = $pdo->prepare('UPDATE todos SET completed = :completed WHERE id = :id');
$stmt->execute(['completed' => $completed, 'id' => $id]);
}
// 獲取所有todo任務
$stmt = $pdo->query('SELECT * FROM todos');
$todos = $stmt->fetchAll();
?>
<!-- 顯示todo列表 -->
<ul>
<?php foreach ($todos as $todo): ?>
<li>
<input type="checkbox" <?= $todo['completed'] ? 'checked' : '' ?> onclick="updateTodo(<?= $todo['id'] ?>, this.checked)">
<?= $todo['task'] ?>
</li>
<?php endforeach; ?>
</ul>
<!-- 添加todo表單 -->
<form method="post" action="">
<input type="text" name="task" required>
<button type="submit" name="action" value="add_todo">Add Todo</button>
</form>
<!-- 更新todo任務的JavaScript函數 -->
<script>
function updateTodo(id, completed) {
fetch('todo.php', {
method: 'POST',
body: JSON.stringify({
id: id,
completed: completed,
action: 'update_todo'
})
});
}
</script>
在上面的示例中,我們使用PDO來連接到數據庫,并在頁面中顯示todo列表。用戶可以添加新的todo任務,并通過復選框來標記任務的完成狀態。當用戶勾選或取消勾選復選框時,JavaScript函數將通過AJAX請求更新數據庫中的數據。