How to use PHP to develop a simple online survey function
In modern society, survey is one of the important means to obtain information and understand user needs. Using PHP to develop a simple and practical online survey function can help us quickly collect data and analyze the results. The following will introduce how to use PHP to implement this function and provide specific code examples.
1. Build the environment
First, you need to build a PHP development environment. You can use XAMPP, WAMP and other software, or install components such as Apache, PHP and MySQL by yourself.
2. Create a database
Create a database in MySQL to store relevant data of the questionnaire. Databases and tables can be created using tools such as phpMyAdmin.
3. Create a questionnaire form
Create a questionnaire form in the database to store the questions and options of the questionnaire. The table structure can be designed as follows:
CREATE TABLE questionnaire
(
id
int(11) NOT NULL AUTO_INCREMENT,
question
varchar(255) NOT NULL,
option1
varchar(255) NOT NULL,
option2
varchar(255) NOT NULL,
option3
varchar(255) NOT NULL,
option4
varchar(255) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
4. Write a questionnaire page
Create a questionnaire page where users can answer questions. You can use HTML and CSS to design the layout and style of the page, and use PHP to dynamically generate questions and options. The following is a sample code:
<h1>在线调查问卷</h1> <form action="submit.php" method="post"> <?php // 查询数据库,获取题目和选项 $conn = mysqli_connect('localhost', 'root', 'password', 'database'); $sql = "SELECT * FROM questionnaire"; $result = mysqli_query($conn, $sql); // 动态生成题目和选项 while ($row = mysqli_fetch_assoc($result)) { echo "<h3>{$row['question']}</h3>"; echo "<input type='radio' name='answer{$row['id']}' value='1'> {$row['option1']}<br>"; echo "<input type='radio' name='answer{$row['id']}' value='2'> {$row['option2']}<br>"; echo "<input type='radio' name='answer{$row['id']}' value='3'> {$row['option3']}<br>"; echo "<input type='radio' name='answer{$row['id']}' value='4'> {$row['option4']}<br><br>"; } ?> <input type="submit" value="提交"> </form>