Есть задание - написать древовидные комментарии на чистом PHP. Застрял на полпути и не знаю как продолжить писать код чтобы наконец-то уже что-то получилось. Написал функции записи комментариев в базу (addComment), их вывода (getComments) и их валидацию (dataValidation), на регулярку не обращайте внимания, будет допилена. Каким образом мне дальше строить алгоритмы для реплаев? Модифицировать функцию addComment или писать новую addReply? Как делать запись родительского id в базу? хелп плиз!!
comments.php (Model)
function getComments()
{
$pdo = new PDO("mysql:host=localhost;dbname=comments;charset=utf8", "root", "");
$sql = "SELECT * FROM comments";
$statement = $pdo->prepare($sql);
$statement->execute();
$comments = $statement->fetchAll(PDO::FETCH_ASSOC);
return $comments;
}
/**
* Adding records from the form to database
*/
function addComment(string $name, string $content): void
{
$pdo = new PDO("mysql:host=localhost;dbname=comments;charset=utf8", "root", "");
$sql = "INSERT INTO comments (name, content) VALUES (:name, :content)";
$statement = $pdo->prepare($sql);
$statement->bindParam("name", $name);
$statement->bindParam("content", $content);
$statement->execute();
}
/**
* Validation of records put into the form
*/
function dataValidation()
{
$errorMessage = [];
$name = trim($_POST['name']);
$content = trim($_POST['content']);
$allowedSymbols = "/^[a-zA-Z-' ]*$/";
$nameLength = 30;
$contentLength = 1000;
if (mb_strlen($name) > $nameLength) {
$errorMessage['name'] = "Name should have less than 30 symbols";
} if (mb_strlen($content) > $contentLength) {
$errorMessage['content'] = "Commentary should have less than 1000 symbols";
} if (empty($name)) {
$errorMessage['name'] = "Enter your name";
} if (empty($content)) {
$errorMessage['content'] = "Enter your commentary";
} if (!preg_match($allowedSymbols, $name)) {
$errorMessage['name'] = "Only letters and white space allowed";
} if (!preg_match($allowedSymbols, $content)) {
$errorMessage['content'] = "Only letters and white space allowed";
}
return $errorMessage;
}
controller.php
<?php
include "../comments.php";
$comments = getComments();
$errorMessage = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$errorMessage = dataValidation();
if (empty($errorMessage)) {
addComment($_POST['name'], $_POST['content']);
}
}
include_once "../index.php";
index.php (View)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tree Comments</title>
<link rel="stylesheet" href="../styles/styles.css">
</head>
<body>
<div class="wrapper">
<div class="navbar">
<a class="logo" href="#">Tree Comments Exercise</a>
</div>
<div class="post">
<h2>Random Post</h2>
<div class="post-row">
Is allowance instantly strangers applauded discourse so. Separate entrance welcomed sensible laughing why
one moderate shy. We seeing piqued garden he.
As in merry at forth least ye stood. And cold sons yet with. Delivered middleton therefore me at. Attachment
companions man way excellence how her pianoforte.
Conveying or northward offending admitting perfectly my. Colonel gravity get thought fat smiling add but.
Wonder twenty hunted and put income set desire expect.
Am cottage calling my is mistake cousins talking up. Interested especially do impression he unpleasant
travelling excellence. All few our knew time done draw ask.
Greatest properly off ham exercise all. Unsatiable invitation its possession nor off. All difficulty
estimating unreserved increasing the solicitude.
</div>
</div>
<div class="commentaries">
<?php include_once "errors.php" ?>
<div class="comments-form">
<h3>Leave a commentary</h3>
<form action="controller.php" method="post">
<div class="input">
<input type="text" name="name" placeholder="Your name" size="53">
</div>
<div class="textarea">
<textarea rows="4" cols="50" name="content" placeholder="Enter Comment"></textarea>
</div>
<div class="submit">
<button type="submit" name="submit_comment" id="submit_comment">Submit</button>
</div>
</form>
</div>
<?php foreach ($comments as $comment): ?>
<div class="comments">
<div class="comment-added-by">
By <b><?= htmlspecialchars($comment['name'], ENT_QUOTES); ?></b> on <?= $comment['date']; ?>
</div>
<hr>
<div class="comment-content">
<p><?= htmlspecialchars($comment['content'], ENT_QUOTES); ?></p>
</div>
<hr>
<div class="comments-reply-button">
<button onclick="document.getElementById('formreply-1').style.display='';">Reply</button>
</div>
</div>
<div class="reply-form">
<div style="display: none" action="#" id="formreply-<?= $comment['id']; ?>">
<div class="reply-name">
<input type="text" placeholder="Your name" size="53">
</div>
<div class="reply-comment">
<textarea rows="2" cols="50" name="reply-content" placeholder="Enter Comment"></textarea>
</div>
<div class="reply-submit">
<button type="submit" id="submit-comment">Submit</button>
</div>
<input type="hidden" value="<?= $comment['id']; ?>">
</div>
</form>
<div class="comments">
<div class="comment-added-by">
By <b>Name</b> on 29-12-2021 00:05
</div>
<hr>
<div class="comment-content">
<p>some reply</p>
</div>
<hr>
<div class="comments-reply-button2">
<button onclick="document.getElementById('formreply-1').style.display='';">Reply</button>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<div class="footer">
<script>
</script>
</div>
</div>
</body>
</html>
В базе данных: id (auto increment), parent_id (default = 0), name, content, date