Bartolomej Bartolomej - 10 days ago 6
PHP Question

Using PHP+MySQL a web-app, where registered, logged user can add some text, which is commentable by other logged, registered users

I want to do using PHP+MySQL a web-app, where registered, logged user can add question or add a comment to the question (unlogged, unregistered user can only read questions and its answers).

The main problem is, how to express in PHP+MySQL the comment to the right straight question. (not to all questions in one, but directly to the right one)

Thank you for all posibilities in way of solving this problem.

Answer

This sounds like a simple database design question.

You are describing 3 tables: users, questions, comments. Comments table has a foreign key of QuestionID, the question in which the comment was posted. It also has a foreign key of PosterID, which is the ID of the user who posted the comment. To view the comments related to a specific question, fetch them by their QuestionID.

Here's a sample SQL query in PHP to fetch comments for a specific question:

$questionId = 5;
$query = "SELECT *
FROM comments
WHERE question_id={$questionId}";
$result = mysqli_query($conn, $query);

I also suggest learning about SQL injection and preferably using PDO prepared statements to construct your queries (The sample I've given uses simple mysqli).