How to develop a simple online questionnaire using MySQL and Python
Sep 20, 2023 am 11:18 AMHow to use MySQL and Python to develop a simple online questionnaire
Introduction
Online questionnaires are widely used in modern society to collect user information Views, feedback and comments. This article will introduce how to use MySQL and Python to develop a simple online questionnaire system, and provide relevant code examples.
1. Database design
-
Create a database named survey:
CREATE DATABASE survey;
Create a database named questions and responses Table:
Create questions table, used to store questionnaire questions:CREATE TABLE questions ( id INT PRIMARY KEY AUTO_INCREMENT, question_text VARCHAR(255) NOT NULL );
Create responses table, used to store user answers:
CREATE TABLE responses ( id INT PRIMARY KEY AUTO_INCREMENT, question_id INT, response_text VARCHAR(255) NOT NULL, FOREIGN KEY (question_id) REFERENCES questions(id) );
2. Python code implementation
Import the necessary libraries:
import mysql.connector from mysql.connector import Error from flask import Flask, request, render_template
Connect to the MySQL database:
def create_connection(): connection = None try: connection = mysql.connector.connect( host='localhost', database='survey', user='your_username', password='your_password' ) if connection.is_connected(): print('Connected to MySQL database') except Error as e: print(e) return connection
Create Flask application and routing:
app = Flask(__name__) @app.route('/') def home(): # 獲取所有的問題 connection = create_connection() cursor = connection.cursor() query = 'SELECT * FROM questions' cursor.execute(query) questions = cursor.fetchall() cursor.close() connection.close() return render_template('index.html', questions=questions) @app.route('/survey', methods=['POST']) def survey(): # 獲取用戶的答案 connection = create_connection() cursor = connection.cursor() response_text = request.form['response'] question_id = request.form['question_id'] query = 'INSERT INTO responses (question_id, response_text) VALUES (%s, %s)' cursor.execute(query, (question_id, response_text)) connection.commit() cursor.close() connection.close() return 'Thank you for your response!' if __name__ == '__main__': app.run()
Create front-end page (index.html):
<!DOCTYPE html> <html> <head> <title>Survey</title> </head> <body> <h1>Survey</h1> <form action="/survey" method="POST"> {% for question in questions %} <p>{{ question[1] }}</p> <input type="hidden" name="question_id" value="{{ question[0] }}"> <input type="text" name="response" required> {% endfor %} <input type="submit" value="Submit"> </form> </body> </html>
3. Run and test
Run the Python code in the terminal:
python survey_app.py
- Visit http://localhost:5000 in the browser to see the questionnaire page.
Conclusion
This article introduces how to use MySQL and Python to develop a simple online questionnaire system. Through database design and related code implementation, users' opinions, feedback and opinions can be easily collected. By enriching the design and functionality of the front-end page, the user experience of the questionnaire can be further improved. I hope this article can be helpful to readers and inspire more innovative ideas.
The above is the detailed content of How to develop a simple online questionnaire using MySQL and Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Pythoncanbeoptimizedformemory-boundoperationsbyreducingoverheadthroughgenerators,efficientdatastructures,andmanagingobjectlifetimes.First,usegeneratorsinsteadofliststoprocesslargedatasetsoneitematatime,avoidingloadingeverythingintomemory.Second,choos

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

Introduction to Statistical Arbitrage Statistical Arbitrage is a trading method that captures price mismatch in the financial market based on mathematical models. Its core philosophy stems from mean regression, that is, asset prices may deviate from long-term trends in the short term, but will eventually return to their historical average. Traders use statistical methods to analyze the correlation between assets and look for portfolios that usually change synchronously. When the price relationship of these assets is abnormally deviated, arbitrage opportunities arise. In the cryptocurrency market, statistical arbitrage is particularly prevalent, mainly due to the inefficiency and drastic fluctuations of the market itself. Unlike traditional financial markets, cryptocurrencies operate around the clock and their prices are highly susceptible to breaking news, social media sentiment and technology upgrades. This constant price fluctuation frequently creates pricing bias and provides arbitrageurs with

iter() is used to obtain the iterator object, and next() is used to obtain the next element; 1. Use iterator() to convert iterable objects such as lists into iterators; 2. Call next() to obtain elements one by one, and trigger StopIteration exception when the elements are exhausted; 3. Use next(iterator, default) to avoid exceptions; 4. Custom iterators need to implement the __iter__() and __next__() methods to control iteration logic; using default values is a common way to safe traversal, and the entire mechanism is concise and practical.

TosecureMySQLeffectively,useobject-levelprivilegestolimituseraccessbasedontheirspecificneeds.Beginbyunderstandingthatobject-levelprivilegesapplytodatabases,tables,orcolumns,offeringfinercontrolthanglobalprivileges.Next,applytheprincipleofleastprivile

The recommended way to read files line by line in Python is to use withopen() and for loops. 1. Use withopen('example.txt','r',encoding='utf-8')asfile: to ensure safe closing of files; 2. Use forlineinfile: to realize line-by-line reading, memory-friendly; 3. Use line.strip() to remove line-by-line characters and whitespace characters; 4. Specify encoding='utf-8' to prevent encoding errors; other techniques include skipping blank lines, reading N lines before, getting line numbers and processing lines according to conditions, and always avoiding manual opening without closing. This method is complete and efficient, suitable for large file processing

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

threading.Timer executes functions asynchronously after a specified delay without blocking the main thread, and is suitable for handling lightweight delays or periodic tasks. ①Basic usage: Create Timer object and call start() method to delay execution of the specified function; ② Cancel task: Calling cancel() method before the task is executed can prevent execution; ③ Repeating execution: Enable periodic operation by encapsulating the RepeatingTimer class; ④ Note: Each Timer starts a new thread, and resources should be managed reasonably. If necessary, call cancel() to avoid memory waste. When the main program exits, you need to pay attention to the influence of non-daemon threads. It is suitable for delayed operations, timeout processing, and simple polling. It is simple but very practical.
