Skip to content

Instantly share code, notes, and snippets.

@codehakase
Created November 4, 2017 13:57
Show Gist options
  • Save codehakase/2b8829a687bdacf5d75b0a3a3781c1ef to your computer and use it in GitHub Desktop.
Save codehakase/2b8829a687bdacf5d75b0a3a3781c1ef to your computer and use it in GitHub Desktop.
A simple todo list app with PHP
<?php
session_start();
// db configs
try {
$db = new PDO('mysql:host=localhost;dbname=DBNAME', 'DBNAME', 'DBPASS');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['add'])) {
$item = $_POST['item'];
if (!empty($item)) {
$newItem = $db->query("INSERT INTO todo (item, status) VALUES ('$item', 0) ");
if ($newItem->rowCount() > 0 ) {
echo "Item added!";
}
}
}
if (isset($_GET['action'])) {
$itemID = $_GET['item'];
if ($_GET['action'] == 'done') {
$updateStatus = $db->query("UPDATE todo SET status = 1 WHERE id = '$itemID' ");
if ($updateStatus->rowCount() > 0) {
echo "item marked as done!";
}
}
elseif ($_GET['action'] == 'delete') {
$deleteItem = $db->query("DELETE FROM todo WHERE id = '$itemID' ");
if ($deleteItem->rowCount() > 0) {
echo "item has been deleted!";
}
}
}
// echo "<pre>";
// var_dump($items);
// echo "</pre>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Todo App</title>
<style>
body {
background: #ccc;
}
.container {
width: 60%;
max-width: 450px;
margin: 0 auto;
background: #fff;
padding: 25px;
margin-top: 16.4vh;
}
.container input[type="text"] {
width: 94%;
padding: 10px;
}
.container input[type="submit"] {
padding: 12px 14px;
background: orange;
outline: none;
cursor: pointer;
font-size: 14px;
color: #fff;
}
.actions {
display: inline-block;
padding: 10px;
}
.item {
display: inline-block;
}
.item-heading {
display: inline-flex;
}
.done {
text-decoration: line-through;
}
</style>
</head>
<body>
<div class="container">
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<input type="text" name="item">
<input type="submit" name="add" value="Add item">
</form>
<div class="todo-items">
<?php $items = $db->query("SELECT * FROM todo"); $c = 0; ?>
<?php if ($items->rowCount() < 1):?>
<i>No items to display</i>
<?php endif;?>
<?php while($data = $items->fetchObject() ):?>
<div class="item">
<h4 class="item-heading <?= $data->status == 1 ? 'done' : ''; ?>"><?= $data->item; ?></h4>
<div class="actions">
<a href="?action=done&item=<?=$data->id;?>">mark done</a>
<a href="?action=delete&item=<?=$data->id;?>">delete</a>
</div>
</div>
<?php $c++; endwhile;?>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment