What are the best practices for storing survey data in a MySQL database using PHP?
When storing survey data in a MySQL database using PHP, it is important to properly sanitize user input to prevent SQL injection attacks. It is also recommended to use prepared statements to securely insert data into the database. Additionally, creating appropriate database tables with the necessary fields for storing survey responses can help organize the data efficiently.
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "survey_db";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Sanitize user input
$survey_response = mysqli_real_escape_string($conn, $_POST['survey_response']);
// Prepare and execute a SQL statement to insert survey data into the database
$stmt = $conn->prepare("INSERT INTO survey_responses (response) VALUES (?)");
$stmt->bind_param("s", $survey_response);
if ($stmt->execute()) {
echo "Survey response stored successfully";
} else {
echo "Error storing survey response: " . $conn->error;
}
// Close the database connection
$stmt->close();
$conn->close();
Keywords
Related Questions
- How can the issue of only one entry being inserted into the database be resolved in the PHP code?
- What are the potential pitfalls of directly accessing and modifying HTML elements in PHP scripts?
- What best practices should be followed when selecting data from a database in PHP, especially when dealing with sensitive information like email addresses?