Home >Backend Development >PHP Tutorial >Online Q&A and knowledge base implementation of PHP and mini programs

Online Q&A and knowledge base implementation of PHP and mini programs

WBOY
WBOYOriginal
2023-07-04 08:05:431548browse

Online Q&A and knowledge base implementation of PHP and mini programs

With the development of the mobile Internet, mini programs have become a very popular form of mobile applications. Questions and answers and knowledge bases are common features in many websites and applications. They allow users to quickly find the information they need and solve problems. This article will introduce how to use PHP and small programs to implement online Q&A and knowledge base functions.

1. Preparation work
Before we start, we need to prepare the following work:

  1. Install the PHP environment and MySQL database;
  2. Create a database to store question and answer data Database table;
  3. Use the mini program development tool to create a mini program project.

2. Create a database table
We need to create a database table to store question and answer data. In the MySQL database, you can execute the following SQL statement to create a data table named "qa":

CREATE TABLE `qa` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `question` varchar(255) NOT NULL,
  `answer` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

This table contains three fields: id (the unique identification of questions and answers), question (question) , answer (answer).

3. PHP backend code

  1. Create a PHP file named "qa.php" and write the following code:
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "your_database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// 处理请求接口
$action = $_GET['action'];
if ($action == 'getQuestions') {
    // 获取问题列表
    $sql = "SELECT * FROM `qa`";
    $result = $conn->query($sql);
    $questions = array();
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $questions[] = array(
                'id' => $row['id'],
                'question' => $row['question'],
                'answer' => $row['answer']
            );
        }
    }
    echo json_encode($questions);
} else if ($action == 'addQuestion') {
    // 添加问题
    $question = $_POST['question'];
    $answer = $_POST['answer'];
    $sql = "INSERT INTO `qa` (`question`, `answer`) VALUES ('$question', '$answer')";
    if ($conn->query($sql) === TRUE) {
        echo 'success';
    } else {
        echo 'error';
    }
} else if ($action == 'deleteQuestion') {
    // 删除问题
    $id = $_POST['id'];
    $sql = "DELETE FROM `qa` WHERE `id` = $id";
    if ($conn->query($sql) === TRUE) {
        echo 'success';
    } else {
        echo 'error';
    }
}

$conn->close();
?>
  1. Put the "qa.php" file written above into the website root directory of your PHP environment.

4. Mini program front-end code

  1. Open the mini program development tool, find the "app.json" file in the project directory, and add the following code (replace "your_website_url" Replace with your website address):
"request": {
    "domain": "your_website_url",
    "tlsVersion": "1.2",
    "timeout": 5000,
    "method": "GET"
}
  1. Create a page named "index" and write the following code:
<view class="container">
    <view class="title">在线问答与知识库</view>
    <view class="form">
        <input placeholder="请输入问题" bindinput="inputQuestion" />
        <input placeholder="请输入答案" bindinput="inputAnswer" />
        <button bindtap="addQuestion">添加问题</button>
    </view>
    <view class="list">
        <view wx:for="{{questionList}}" wx:key="id" class="item">
            <view class="question">{{item.question}}</view>
            <view class="answer">{{item.answer}}</view>
            <button bindtap="deleteQuestion">删除</button>
        </view>
    </view>
</view>
  1. in " Index.js" file, write the following code:
Page({
  data: {
    questionList: [],
    question: '',
    answer: ''
  },

  onLoad: function () {
    this.getQuestionList();
  },

  getQuestionList: function () {
    wx.request({
      url: 'your_website_url/qa.php?action=getQuestions',
      success: (res) => {
        this.setData({
          questionList: res.data
        })
      }
    })
  },

  inputQuestion: function (e) {
    this.setData({
      question: e.detail.value
    })
  },

  inputAnswer: function (e) {
    this.setData({
      answer: e.detail.value
    })
  },

  addQuestion: function () {
    wx.request({
      url: 'your_website_url/qa.php?action=addQuestion',
      method: 'POST',
      data: {
        question: this.data.question,
        answer: this.data.answer
      },
      success: (res) => {
        if (res.data == 'success') {
          this.getQuestionList();
          this.setData({
            question: '',
            answer: ''
          })
        }
      }
    })
  },

  deleteQuestion: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.request({
      url: 'your_website_url/qa.php?action=deleteQuestion',
      method: 'POST',
      data: {
        id: id
      },
      success: (res) => {
        if (res.data == 'success') {
          this.getQuestionList();
        }
      }
    })
  }
})

5. Test run

  1. Use the mini program development tool to preview the mini program and you can see a simple Q&A list Interface;
  2. Enter questions and answers, click the "Add Question" button, the question will be added to the database;
  3. Click the "Delete" button to the right of the question, the question will be removed from the database deleted from the database.

Through the above steps, we have successfully implemented a simple online Q&A and knowledge base function. Users can easily browse and add questions in the mini program. Of course, this is just a basic implementation and you can expand and optimize it according to your needs. I hope this article can be helpful to PHP and small program development!

The above is the detailed content of Online Q&A and knowledge base implementation of PHP and mini programs. 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