Home  >  Article  >  Backend Development  >  How to develop a simple questionnaire function using PHP

How to develop a simple questionnaire function using PHP

WBOY
WBOYOriginal
2023-09-21 14:04:541214browse

How to develop a simple questionnaire function using PHP

How to use PHP to develop a simple questionnaire function, specific code examples are required

Questionnaire is a common data collection method, widely used in market research, academic Research, public opinion monitoring and other fields. In the Internet age, conducting questionnaire surveys through web pages has become mainstream. As a commonly used server-side scripting language, PHP has functions such as processing form data and database operations, and is very suitable for developing simple questionnaire functions.

This article will introduce how to use PHP to develop a simple questionnaire function, including creating questionnaires, collecting user responses and displaying survey results. The following are specific implementation steps and sample code.

Step 1: Create a database table
First, we need to create a database to store questionnaire-related data. You can use MySQL or other relational databases to create the following two tables:

  1. surveys: used to store basic information about questionnaires, including fields such as questionnaire title, description, and creation time.

    CREATE TABLE surveys (
     id INT AUTO_INCREMENT PRIMARY KEY,
     title VARCHAR(255) NOT NULL,
     description TEXT,
     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    );
  2. questions: Used to store questions and option information for each questionnaire, including fields such as question content, question type, and option list. The survey_id field is used to establish a foreign key association with the surveys table.

    CREATE TABLE questions (
     id INT AUTO_INCREMENT PRIMARY KEY,
     survey_id INT NOT NULL,
     question TEXT,
     type ENUM('单选', '多选', '文本') NOT NULL,
     options TEXT,
     FOREIGN KEY (survey_id) REFERENCES surveys(id)
    );

Step 2: Create a questionnaire page
Next, we need to create a web page for displaying the questionnaire. Users can select answers and submit questionnaires on this page. Below is an example of a simple survey page (survey.php).

<?php
// 连接数据库
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");

// 获取问卷信息
$surveyId = $_GET['id']; // 从URL参数获取问卷ID
$surveyStmt = $pdo->prepare("SELECT * FROM surveys WHERE id = :id");
$surveyStmt->bindParam(':id', $surveyId);
$surveyStmt->execute();
$survey = $surveyStmt->fetch();

// 获取问题列表
$questionsStmt = $pdo->prepare("SELECT * FROM questions WHERE survey_id = :survey_id");
$questionsStmt->bindParam(':survey_id', $surveyId);
$questionsStmt->execute();
$questions = $questionsStmt->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $survey['title']; ?></title>
</head>
<body>
    <h1><?php echo $survey['title']; ?></h1>
    <p><?php echo $survey['description']; ?></p>

    <form action="submit.php" method="POST">
        <?php foreach ($questions as $question): ?>
            <h3><?php echo $question['question']; ?></h3>
            <?php if ($question['type'] == '单选' || $question['type'] == '多选'): ?>
                <?php $options = explode("
", $question['options']); ?>
                <?php foreach ($options as $option): ?>
                    <label>
                        <input type="<?php echo $question['type'] == '单选' ? 'radio' : 'checkbox'; ?>" name="answers[<?php echo $question['id']; ?>][]" value="<?php echo $option; ?>">
                        <?php echo $option; ?>
                    </label>
                <?php endforeach; ?>
            <?php else: ?>
                <textarea name="answers[<?php echo $question['id']; ?>]"></textarea>
            <?php endif; ?>
        <?php endforeach; ?>

        <input type="hidden" name="survey_id" value="<?php echo $surveyId; ?>">
        <input type="submit" value="提交">
    </form>
</body>
</html>

Step 3: Process questionnaire data
After the user submits the questionnaire, we need to save the answer data to the database. The following is an example of a simple data processing page (submit.php).

<?php
// 连接数据库
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");

// 获取问卷ID
$surveyId = $_POST['survey_id'];

// 处理问题答案
foreach ($_POST['answers'] as $questionId => $answer) {
    $answer = is_array($answer) ? implode(', ', $answer) : $answer;
    
    $answerStmt = $pdo->prepare("INSERT INTO answers (survey_id, question_id, answer) VALUES (?, ?, ?)");
    $answerStmt->execute([$surveyId, $questionId, $answer]);
}

// 跳转到结果页面
header("Location: result.php?id=$surveyId");

Step 4: Display the survey results
Finally, we can create a page to display the results of the survey. Below is a simple results page example (result.php).

<?php
// 连接数据库
$pdo = new PDO("mysql:host=localhost;dbname=test", "username", "password");

// 获取问卷ID
$surveyId = $_GET['id'];

// 获取问卷信息
$surveyStmt = $pdo->prepare("SELECT * FROM surveys WHERE id = :id");
$surveyStmt->bindParam(':id', $surveyId);
$surveyStmt->execute();
$survey = $surveyStmt->fetch();

// 获取问题列表和答案统计
$questionsStmt = $pdo->prepare("
    SELECT q.id, q.question, q.type, q.options, a.answer, COUNT(*) AS count
    FROM questions q
    LEFT JOIN answers a ON q.id = a.question_id
    WHERE q.survey_id = :survey_id
    GROUP BY q.id, a.answer
");
$questionsStmt->bindParam(':survey_id', $surveyId);
$questionsStmt->execute();
$questions = $questionsStmt->fetchAll();
?>

<!DOCTYPE html>
<html>
<head>
    <title><?php echo $survey['title']; ?> - 结果</title>
</head>
<body>
    <h1><?php echo $survey['title']; ?> - 结果</h1>
    
    <?php foreach ($questions as $question): ?>
        <h3><?php echo $question['question']; ?></h3>
        <?php if ($question['type'] == '单选' || $question['type'] == '多选'): ?>
            <?php $options = explode("
", $question['options']); ?>
            <ul>
                <?php foreach ($options as $option): ?>
                    <li><?php echo $option; ?> - <?php echo $question['count']; ?></li>
                <?php endforeach; ?>
            </ul>
        <?php else: ?>
            <p><?php echo $question['answer']; ?></p>
        <?php endif; ?>
    <?php endforeach; ?>
</body>
</html>

Using the above code example, we can quickly develop a simple questionnaire function. Users can select answers on the questionnaire page and submit. The system will save the answers to the database and display statistical information on the results page.

Of course, the above code is just a simple example, and issues such as security and data verification may also need to be considered in actual projects. At the same time, the code can be optimized and expanded according to actual needs.

I hope this article will help you understand and use PHP to develop a simple questionnaire function!

The above is the detailed content of How to develop a simple questionnaire function using PHP. 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