<?php
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=crud_project", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
if(isset($_POST['add'])){
$newTitle = $_POST['title'];
$newContent = $_POST['content'];
$stmt = $conn->prepare("INSERT INTO entries (user_id, title, content) VALUES (1, '$newTitle', '$newContent')");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_POST['delete'])){
$delete_id = $_POST['delete'];
$stmt = $conn->prepare("DELETE FROM entries WHERE id = ?");
$stmt->execute([$delete_id]);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
if(isset($_POST['update']) && isset($_POST['title']) && isset($_POST['content'])){
$stmt = $conn->prepare("UPDATE entries SET title = ?, content = ? WHERE id = ?");
$stmt->execute([$_POST['title'], $_POST['content'], $_GET['edit']]);
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Test Uebung</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">user_id</th>
<th scope="col">title</th>
<th scope="col">content</th>
<th scope="col">created_at</th>
<th scope="col">options</th>
</tr>
</thead>
<tbody>
<?php
$stmt = $conn->prepare("SELECT * FROM entries");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "<form method='get'>";
echo "<td><button class='btn btn-primary' name='edit' value='" . $row['id'] . "'> Details </button></td>";
echo "</form>";
echo "<form method='post'>";
echo "<td><button class='btn btn-danger' name='delete' value='" . $row['id'] . "'> Delete </button></td>";
echo "</form>";
echo "</tr>";
}
?>