Skip to content

Instantly share code, notes, and snippets.

@Garciat
Last active January 25, 2026 11:24
Show Gist options
  • Select an option

  • Save Garciat/31c9f940aa139bdeaebf9e47c2e67842 to your computer and use it in GitHub Desktop.

Select an option

Save Garciat/31c9f940aa139bdeaebf9e47c2e67842 to your computer and use it in GitHub Desktop.
<?php
// connect to the database
$pdo = new PDO('sqlite:todo.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// create the table if it doesn't exist
$pdo->exec("CREATE TABLE IF NOT EXISTS todos (
id INTEGER PRIMARY KEY,
task TEXT NOT NULL,
completed INTEGER NOT NULL DEFAULT 0
)");
// handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$task = $_POST['task'];
$stmt = $pdo->prepare("INSERT INTO todos (task) VALUES (:task)");
$stmt->execute([':task' => $task]);
// redirect to avoid form resubmission
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
// handle task completion
if (isset($_GET['complete'])) {
$id = $_GET['complete'];
$stmt = $pdo->prepare("UPDATE todos SET completed = 1 WHERE id = :id");
$stmt->execute([':id' => $id]);
// redirect to avoid form resubmission
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
// handle task deletion
if (isset($_GET['delete'])) {
$id = $_GET['delete'];
$stmt = $pdo->prepare("DELETE FROM todos WHERE id = :id");
$stmt->execute([':id' => $id]);
// redirect to avoid form resubmission
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
// fetch all todos
$stmt = $pdo->query("SELECT * FROM todos");
$todos = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Todo App</title>
</head>
<body>
<h1>Todo App</h1>
<form method="POST">
<input type="text" name="task" placeholder="Enter a new task" required>
<button type="submit">Add Task</button>
</form>
<ul>
<?php foreach ($todos as $todo): ?>
<li>
<?php if ($todo['completed']): ?>
<s><?php echo htmlspecialchars($todo['task']); ?></s>
<?php else: ?>
<?php echo htmlspecialchars($todo['task']); ?>
<a href="?complete=<?php echo $todo['id']; ?>">Complete</a>
<?php endif; ?>
<a href="?delete=<?php echo $todo['id']; ?>">Delete</a>
</li>
<?php endforeach; ?>
</ul>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment