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:
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"] . "
"; echo "是"; echo "否"; echo "
"; } } // 保存用户回答 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:
在线问卷调查
It should be noted that theaction
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!