Table of Contents
- 结果
Home Backend Development PHP Tutorial How to develop a simple questionnaire function using PHP

How to develop a simple questionnaire function using PHP

Sep 21, 2023 pm 02:04 PM
Survey function Simple development php questionnaire

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
    );
    Copy after login
  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)
    );
    Copy after login

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>
Copy after login

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");
Copy after login

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 id="php-echo-survey-title-结果"><?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>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP to develop simple questionnaire surveys and statistical functions How to use PHP to develop simple questionnaire surveys and statistical functions Sep 21, 2023 pm 01:31 PM

How to use PHP to develop simple questionnaire surveys and statistical functions In recent years, with the popularity and development of the Internet, questionnaire surveys have become a common method of data collection. As a common server-side programming language, PHP is easy to learn and use, and is widely used to develop Web applications. This article will introduce how to use PHP to develop a simple questionnaire survey and statistical functions, and provide specific code examples. 1. Database design First, we need to design a suitable database to store relevant data of the questionnaire survey. Fake

How to develop a simple online conference system using PHP How to develop a simple online conference system using PHP Sep 20, 2023 pm 03:37 PM

How to use PHP to develop a simple online conference system. With the rapid development of the Internet, online conferencing has become an important tool for more and more companies and individuals to communicate and collaborate. In order to meet the needs of users, it is necessary to develop a simple and easy-to-use online conference system. This article will introduce how to use PHP to develop a simple online meeting system and provide specific code examples. 1. Requirements analysis and function sorting Before starting development, we need to conduct needs analysis and function sorting first. A simple online conference system should have the following functions

How to use PHP to develop a simple online questionnaire function How to use PHP to develop a simple online questionnaire function Sep 20, 2023 pm 01:39 PM

How to use PHP to develop a simple online questionnaire survey function With the continuous development and popularization of the Internet, online questionnaire surveys have become a common data collection method. As a commonly used programming language, PHP has flexibility and ease of use, and can play an important role when developing online questionnaire functions. This article will introduce how to use PHP to develop a simple online questionnaire function and provide specific code examples. 1. Create database and data table First, we need to create a database to store the relevant information of the questionnaire survey.

How to develop a simple questionnaire function using PHP How to develop a simple questionnaire function using PHP Sep 21, 2023 pm 02:04 PM

How to use PHP to develop a simple questionnaire function requires specific code examples. Questionnaire is a common data collection method and is 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,

How to use PHP to develop a simple voting system and result statistics function How to use PHP to develop a simple voting system and result statistics function Sep 21, 2023 pm 01:01 PM

How to use PHP to develop a simple voting system and result statistics function? 1. Introduction: Voting system is a common function widely used in various scenarios, such as corporate employee selection, student representative election, etc. This article will introduce how to use PHP to develop a simple voting system and implement the result statistics function. 2. Set up the environment: Before starting, you need to ensure that the PHP environment has been installed locally or on the server. If it is not installed, you can refer to the relevant documents for installation and configuration. 3. Database design: Before you start writing code, you need

How to use PHP to develop a simple account and password generator How to use PHP to develop a simple account and password generator Sep 24, 2023 pm 02:46 PM

How to use PHP to develop a simple account and password generator. With the development of the Internet, people increasingly rely on account numbers and passwords to manage personal information and data. In order to ensure the security of our accounts, we usually choose more complex and random passwords. However, it’s not easy to remember all the different account numbers and passwords. Therefore, it is very useful to develop a tool that can generate random account passwords. In this article, I will introduce to you how to use PHP to develop a simple account and password generator. This generator will be able to customize the user's

How to develop a simple logistics management system using Go language How to develop a simple logistics management system using Go language Nov 20, 2023 pm 12:48 PM

How to develop a simple logistics management system using Go language. With the rise of e-commerce, the logistics industry is developing rapidly. In order to improve logistics transportation efficiency, optimize distribution processes and reduce costs, many logistics companies have begun to use information technology for management and operations. In this article, we will introduce how to develop a simple logistics management system using Go language. 1. System requirements analysis Before starting to develop the logistics management system, we first need to clarify the basic requirements of the system. A simple logistics management system should include the following functions: Express order

How to use PHP to develop a simple online ticket booking function How to use PHP to develop a simple online ticket booking function Sep 21, 2023 pm 12:57 PM

How to use PHP to develop a simple online ticket booking function In modern society, more and more people choose to book tickets online to save time and convenience. For individuals or small businesses, developing a simple online ticket booking function is a good choice. This article will teach you how to use PHP to develop a simple online ticket booking function and provide specific code examples. Step 1: Create database and tables First, we need to create a database to store ticket-related data. Open your MySQL administration tool (such as phpMyAdmin)

See all articles