您好,欢迎访问一九零五行业门户网

使用 PHP 开发知识问答网站中的问题答案采纳和推荐功能

使用 php 开发知识问答网站中的问题答案采纳和推荐功能
在知识问答类网站中,用户提出问题,其他用户提供回答。常常会出现多个回答中有一个或多个被提问者或其他用户认可为最佳答案的情况。因此,为了更好地展示和管理问题的答案,我们将在本文中介绍如何使用 php 开发问题答案的采纳和推荐功能。
数据库设计首先,我们需要设计数据库来存储问题和答案的相关信息。在这里,我们创建三个表格。
questions 表存储问题信息,例如问题 id、标题、内容、提问者 id、提问时间等。answers 表存储答案信息,例如答案 id、问题 id、回答内容、回答者 id、回答时间等。accepted_answers 表用于存储被采纳的答案信息,其中包含问题 id、被采纳答案 id。以下是数据库结构的示例:
create table questions ( id int primary key auto_increment, title varchar(255), content text, owner_id int, created_at timestamp default current_timestamp);create table answers ( id int primary key auto_increment, question_id int, content text, owner_id int, created_at timestamp default current_timestamp);create table accepted_answers ( question_id int primary key, answer_id int);
问题页面开发在问题详情页面上,我们需要显示问题的标题、内容以及相关答案。对于当前问题,我们还需要显示被采纳的答案(如果有的话)。
首先,我们要获取问题的信息并显示在页面上。我们可以使用以下代码示例:
<?php// 获取问题 id$questionid = $_get['id'];// 获取问题信息$questionquery = "select * from questions where id = :id";$questionstmt = $pdo->prepare($questionquery);$questionstmt->bindparam(':id', $questionid, pdo::param_int);$questionstmt->execute();$question = $questionstmt->fetch(pdo::fetch_assoc);// 显示问题标题和内容echo "<h1>" . $question['title'] . "</h1>";echo "<p>" . $question['content'] . "</p>";// 获取问题的回答信息$answersquery = "select * from answers where question_id = :question_id";$answersstmt = $pdo->prepare($answersquery);$answersstmt->bindparam(':question_id', $questionid, pdo::param_int);$answersstmt->execute();$answers = $answersstmt->fetchall(pdo::fetch_assoc);// 显示回答列表foreach ($answers as $answer) { echo "<div>"; echo "<p>" . $answer['content'] . "</p>"; // 检查答案是否被采纳 if ($answer['id'] === $question['accepted_answer_id']) { echo "<span>已采纳</span>"; } else { // 显示采纳按钮 echo "<a href='accept-answer.php?question=" . $questionid . "&answer=" . $answer['id'] . "'>采纳该答案</a>"; } echo "</div>";}?>
以上代码中,我们首先获取问题的信息并展示在页面上。然后,获取问题相关的答案并逐个显示。对于每个答案,我们检查其是否被采纳。如被采纳,则显示“已采纳”标志;反之,则显示一个标签,点击该标签将调用 accept-answer.php 进行答案的采纳。
采纳答案的处理在 accept-answer.php 文件中,我们需要处理答案的采纳请求,并更新 accepted_answers 表。
以下是处理采纳答案请求的代码示例:
<?php// 获取问题 id 和答案 id$questionid = $_get['question'];$answerid = $_get['answer'];// 将答案 id 更新为被采纳$acceptanswerquery = "update accepted_answers set answer_id = :answer_id where question_id = :question_id";$acceptanswerstmt = $pdo->prepare($acceptanswerquery);$acceptanswerstmt->bindparam(':answer_id', $answerid, pdo::param_int);$acceptanswerstmt->bindparam(':question_id', $questionid, pdo::param_int);$acceptanswerstmt->execute();// 返回问题详情页header("location: question.php?id=" . $questionid);?>
在上述代码中,我们首先获取问题和答案的 id。然后,通过执行 sql 语句将答案 id 更新为被采纳的答案。最后,我们重定向到问题详情页,刷新页面以显示最新的采纳状态。
通过以上的步骤,我们成功实现了知识问答网站中问题答案的采纳和推荐功能。用户可以在问题详情页中采纳自己认可的答案,并通过此功能提升问题和答案的质量。这有助于用户更好地获取和分享知识。
以上就是使用 php 开发知识问答网站中的问题答案采纳和推荐功能。的详细内容。
其它类似信息

推荐信息