Home  >  Article  >  Backend Development  >  How to use PHP to develop a simple online question and answer system

How to use PHP to develop a simple online question and answer system

WBOY
WBOYOriginal
2023-09-21 16:28:49788browse

How to use PHP to develop a simple online question and answer system

How to use PHP to develop a simple online question and answer system?

In the Internet era, Q&A communities have become a common way for people to obtain various knowledge and solve problems. Many websites offer Q&A features where users can ask questions and get answers from other users. This article will introduce how to use PHP to develop a simple online question and answer system and provide specific code examples.

First, we need to create a database to store questions and answers. This can be achieved using MySQL or other relational databases. Below is an example SQL statement to create a question table and an answer table.

CREATE TABLE questions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE answers (
    id INT AUTO_INCREMENT PRIMARY KEY,
    question_id INT NOT NULL,
    content TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (question_id) REFERENCES questions(id)
);

Next, we need to create a PHP file to handle the addition, deletion, modification and checking of questions and answers. The following is a simple sample code:

<?php
// 连接数据库
$host = 'localhost';
$db = 'question_answer';
$user = 'root';
$password = 'password';
$conn = new PDO("mysql:host=$host;dbname=$db", $user, $password);

// 添加问题
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['title']) && isset($_POST['content'])) {
    $title = $_POST['title'];
    $content = $_POST['content'];

    $sql = "INSERT INTO questions (title, content) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$title, $content]);
    $questionId = $conn->lastInsertId();

    // 返回问题ID
    echo json_encode(['questionId' => $questionId]);
    exit;
}

// 获取问题和答案
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['questionId'])) {
    $questionId = $_GET['questionId'];

    // 获取问题
    $sql = "SELECT * FROM questions WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$questionId]);
    $question = $stmt->fetch(PDO::FETCH_ASSOC);

    // 获取答案
    $sql = "SELECT * FROM answers WHERE question_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$questionId]);
    $answers = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 返回问题和答案
    echo json_encode(['question' => $question, 'answers' => $answers]);
    exit;
}

// 添加答案
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['questionId']) && isset($_POST['content'])) {
    $questionId = $_POST['questionId'];
    $content = $_POST['content'];

    $sql = "INSERT INTO answers (question_id, content) VALUES (?, ?)";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$questionId, $content]);

    // 返回成功
    echo json_encode(['success' => true]);
    exit;
}

// 删除问题
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['deleteQuestionId'])) {
    $questionId = $_POST['deleteQuestionId'];

    // 删除问题
    $sql = "DELETE FROM questions WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$questionId]);

    // 删除相关答案
    $sql = "DELETE FROM answers WHERE question_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$questionId]);

    // 返回成功
    echo json_encode(['success' => true]);
    exit;
}
?>

In the above code, we use PDO to connect to the database and use prepared statements to prevent SQL injection attacks.

Next, we can create a front-end page to display questions and answers, and provide the functionality to add and delete questions. The following is a simple front-end page example:

<!DOCTYPE html>
<html>
<head>
    <title>在线问答系统</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <h1>在线问答系统</h1>

    <!-- 添加问题表单 -->
    <form id="addQuestionForm">
        <input type="text" name="title" placeholder="问题标题" required>
        <textarea name="content" placeholder="问题内容" required></textarea>
        <button type="submit">添加问题</button>
    </form>

    <!-- 问题列表 -->
    <ul id="questionList"></ul>

    <script>
        // 添加问题
        $('#addQuestionForm').submit(function(e) {
            e.preventDefault();

            $.post('qa.php', $(this).serialize(), function(response) {
                // 更新问题列表
                fetchQuestionList();
                // 清空表单
                $('#addQuestionForm')[0].reset();
            }, 'json');
        });

        // 获取问题列表
        function fetchQuestionList() {
            $.get('qa.php', function(response) {
                var questionList = '';
                for (var i = 0; i < response.length; i++) {
                    var question = response[i];
                    var questionItem = '<li>'
                        + '<h3>' + question.title + '</h3>'
                        + '<p>' + question.content + '</p>'
                        + '<button onclick="deleteQuestion(' + question.id + ')">删除</button>'
                        + '</li>';

                    questionList += questionItem;
                }

                $('#questionList').html(questionList);
            }, 'json');
        }

        // 删除问题
        function deleteQuestion(questionId) {
            if (confirm('确定要删除该问题及相关答案吗?')) {
                $.post('qa.php', { deleteQuestionId: questionId }, function(response) {
                    fetchQuestionList();
                }, 'json');
            }
        }

        // 页面加载时获取问题列表
        $(function() {
            fetchQuestionList();
        });
    </script>
</body>
</html>

In the above code, we use jQuery to send AJAX requests to communicate with the server, and use DOM operations to dynamically update the page content.

To sum up, through the above PHP and HTML code examples, we can implement a simple online question and answer system. Of course, this is just a basic example. The actual question and answer system also needs to consider more functional and security issues. I hope this article can help you get started with PHP development and inspire you to build a more complete online question and answer system.

The above is the detailed content of How to use PHP to develop a simple online question and answer system. 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