search
HomeBackend DevelopmentPHP TutorialHow 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
php developmentOnline questionnaireSurvey function

How to use PHP to develop a simple online questionnaire function

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 questionnaire-related data. In the MySQL database, you can use the following SQL statement to create a database named questionsnaire, and a data table named questions.

CREATE DATABASE questionnaire;
USE questionnaire;
CREATE TABLE questions (
    id INT AUTO_INCREMENT PRIMARY KEY,
    question VARCHAR(255) NOT NULL
);

 2. Write PHP code to display the questionnaire and save user answers

Next, we need to write PHP code to display the questionnaire and save user answers. The following is a simple sample code:

<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "questionnaire";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("连接失败:" . $conn->connect_error);
}

// 获取问卷题目
$sql = "SELECT * FROM questions";
$result = $conn->query($sql);

// 显示问卷题目
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        echo $row["id"] . ". " . $row["question"] . "<br>";
        echo "<input type='radio' name='answer_" . $row["id"] . "' value='yes'>是";
        echo "<input type='radio' name='answer_" . $row["id"] . "' value='no'>否";
        echo "<br><br>";
    }
}

// 保存用户回答
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    foreach ($_POST as $key => $value) {
        if (strpos($key, 'answer_') === 0) {
            $questionId = substr($key, strlen('answer_'));
            $answer = $value;
            $sql = "INSERT INTO responses (question_id, answer) VALUES ('$questionId', '$answer')";
            if ($conn->query($sql) !== TRUE) {
                echo "保存失败:" . $conn->error;
            }
        }
    }
}

// 关闭数据库连接
$conn->close();
?>

 3. Create a questionnaire page

Finally, we need to create a questionnaire page to display the questionnaire and submit the user's answers. The following is a simple HTML code example:

<!DOCTYPE html>
<html>
<head>
    <title>在线问卷调查</title>
</head>
<body>
    <form action="survey.php" method="post">
        <?php include 'survey.php'; ?>
        <input type="submit" value="提交">
    </form>
</body>
</html>

It should be noted that the action attribute in the above code should be consistent with the file name of the questionnaire page.

So far, we have completed a simple online questionnaire function developed using PHP. Users can select responses on the survey page and click the submit button to save the responses to the database. Developers can obtain user response data by querying the database.

Summary:

This article introduces how to use PHP to write a simple online questionnaire function and provides specific code examples. By studying these sample codes, you can learn about common development steps such as creating databases and data tables, displaying questionnaire questions, saving user responses, and creating questionnaire pages. I hope this article can help you understand and use PHP to develop online questionnaire functions.

The above is the detailed content of How to use PHP to develop a simple online questionnaire function. 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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),