Home  >  Article  >  Backend Development  >  PHP implements the question marking and collection functions in the knowledge Q&A website.

PHP implements the question marking and collection functions in the knowledge Q&A website.

王林
王林Original
2023-07-02 08:05:131271browse

PHP realizes the question marking and collection functions in the knowledge Q&A website

With the rapid development of the Internet, the knowledge Q&A website has become an important platform for people to obtain and share knowledge. On these websites, users can ask questions, answer questions, browse and search related questions and answers, etc. In order to improve user experience and functional completeness, issue marking and collection functions have become an integral part. This article will introduce how to use PHP language to implement these functions and provide corresponding code examples.

The question tagging function allows users to label questions to facilitate subsequent search and classification. During the implementation process, we can use the tag association table to implement the many-to-many relationship between questions and tags. The following is an example database table structure:

CREATE TABLE `questions` (
  `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `title` varchar(255) NOT NULL,
  `content` text NOT NULL
);

CREATE TABLE `tags` (
  `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(50) NOT NULL
);

CREATE TABLE `question_tags` (
  `question_id` int(11) UNSIGNED,
  `tag_id` int(11) UNSIGNED,
  FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`tag_id`) REFERENCES `tags`(`id`) ON DELETE CASCADE
);

In the question page, we can provide an input box that allows users to enter tags and give automatic completion suggestions during the input process. The following is a sample code for a simple implementation:

<label>标签:</label>
<input type="text" id="tag-input" name="tags" autocomplete="off">
<div id="tag-suggestions"></div>

<script>
    $(document).ready(function() {
        $('#tag-input').on('keyup', function() {
            var keyword = $(this).val();
            $('#tag-suggestions').empty();
            
            if (keyword.length > 0) {
                $.ajax({
                    url: 'tag_suggestions.php',
                    data: {keyword: keyword},
                    dataType: 'json',
                    success: function(response) {
                        if (response.length > 0) {
                            $.each(response, function(index, value) {
                                $('#tag-suggestions').append('<div class="tag-suggestion">' + value.name + '</div>');
                            });
                        }
                    }
                });
            }
        });
        
        $(document).on('click', '.tag-suggestion', function() {
            var tagName = $(this).text();
            var tagInput = $('#tag-input');
            var currentTags = tagInput.val().split(',');
            
            if ($.inArray(tagName, currentTags) === -1) {
                tagInput.val(currentTags.join(',') + ',' + tagName);
            }
            
            $('#tag-suggestions').empty();
        });
    });
</script>

In the above code, we use the jQuery library to listen to the keyboard input events of the input box. After each input, call tag_suggestions.php to implement the server-side tag suggestion function and display the results on the page.

In the tag_suggestions.php file, we can implement the logic of tag suggestions. The following is an example code:

<?php
$keyword = $_GET['keyword'];

// 模拟从数据库中查询标签建议
$tags = array();
if ($keyword === 'php') {
    $tags[] = array('name' => 'PHP');
    $tags[] = array('name' => 'PHP框架');
} elseif ($keyword === 'javascript') {
    $tags[] = array('name' => 'JavaScript');
    $tags[] = array('name' => 'JavaScript库');
}

echo json_encode($tags);
?>

In the collection function, users can collect questions they are interested in for subsequent viewing. In order to implement this function, we can create a separate favorites table to record the user's favorite questions. The following is a simple database table structure example:

CREATE TABLE `favorites` (
  `id` int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  `user_id` int(11) UNSIGNED,
  `question_id` int(11) UNSIGNED,
  FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
  FOREIGN KEY (`question_id`) REFERENCES `questions`(`id`) ON DELETE CASCADE
);

In the question page, we can provide a favorite button for each question. When the button is clicked, the question ID will be sent to the server for processing. The following is an example code:

<button class="favorite-button" data-question-id="1">收藏</button>

<script>
    $(document).ready(function() {
        $('.favorite-button').on('click', function() {
            var questionId = $(this).data('question-id');
            
            $.ajax({
                url: 'favorite_question.php',
                data: {questionId: questionId},
                success: function(response) {
                    alert(response);
                }
            });
        });
    });
</script>

In the favorite_question.php file, we can implement the logic of question collection. The following is the code of an example:

<?php
$questionId = $_GET['questionId'];

// 假设当前用户已经登录,获取当前用户的ID
$userId = 1;

// 将问题ID和用户ID插入到favorites表中
$connection = new mysqli('localhost', 'username', 'password', 'database');
$statement = $connection->prepare('INSERT INTO favorites (user_id, question_id) VALUES (?, ?)');
$statement->bind_param('ii', $userId, $questionId);
$statement->execute();

if ($statement->affected_rows > 0) {
    echo '问题已收藏';
} else {
    echo '收藏失败';
}

$statement->close();
$connection->close();
?>

In this article, we introduce how to use PHP to implement question marking and collection functions in a knowledge Q&A website. Through code examples, we show how to implement the front-end input suggestions and click the favorite button functions, and provide the corresponding server-side processing logic. The implementation of these functions will enhance the practicality and user experience of the knowledge question and answer website and provide users with better services.

The above is the detailed content of PHP implements the question marking and collection functions in the knowledge Q&A website.. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn