Hello everyone
I am new to php mvc and I hope someone can help me.
I have been playing around with php mvc after learning oopMy web app is CRUD capable so now I want to add a comment system to the posts. So far, I can display the form beneath the post for logged in users, and the comment is saved to database. But I am battling to get it to display on the post page. Here is my code and thanx in advance:
/**
* Comments Model
*/
public static function addComment() {
try {
$sql = ("INSERT INTO comments (id, parent_id, user_id, body, published)
VALUES (:id, :parent_id, :user_id, :body, :published)");
$db = static::getDBUserContent();
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_REQUEST['id'], PDO::PARAM_INT);
$stmt->bindParam(':parent_id', $_REQUEST['parent_id'], PDO::PARAM_INT);
$stmt->bindParam(':user_id', $_REQUEST['user_id'], PDO::PARAM_INT);
$stmt->bindParam(':body', $_REQUEST['body'], PDO::PARAM_STR);
$stmt->bindParam(':published', $_REQUEST['published'], PDO::PARAM_INT);
return $stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
return true;
}
/**
* List all Comments for a blog post
*
* @return array
*/
public static function getComments() {
try {
$db = static::getDBUserContent();
$stmt = $db->query('SELECT *,
id as id,
blog_id as blog_id
FROM comments
LEFT JOIN userContent.blogs
ON id = blogs.id
WHERE published=1
ORDER BY date DESC
');
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
} catch (PDOException $e) {
echo $e->getMessage();
}
}
/**
* Comments Controller
*/
// Add a comment
public function addCommentAction() {
$comment = new BlogsModel($_POST);
if ($comment->addComment()) {
$this->redirect('/');
}
}
// This is where I am stuck
public function indexAction() {
$comments = new BlogsModel::getComments($id);
}
<!-- Add a comment form -->
<form action="/comments/add" id="newComment" method="POST">
<input type="hidden" name="blogID" value="{{ blog.blogID }}">
<input type="hidden" name="user_id" value="{{ current_user.userID }}">
<input type="hidden" name="parent_id" value="{{ comment.commentID }}">
<input type="hidden" name="published" value="1">
<textarea name="body" id="body" cols="30" rows="10"></textarea>
<button type="submit">Create</button>
</form>
<!-- List comments for this post -->
{% for comment in comments %}
{% if comment.id == comment.blog_id %}
{{ comment.body }}
{{ comment.fname }}
{% endif %}
{% endfor %}
My mysql comments table:
id, blog_id, parent_id, user_id, body, date, published