What are the necessary steps to create a functional PHP survey script that involves calculations and database interactions?
To create a functional PHP survey script that involves calculations and database interactions, you will need to first design the survey questions and structure the database to store the responses. Then, you will need to create the PHP script that will handle the form submission, calculate any necessary values based on the responses, and store the data in the database.
<?php
// Connect to the 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);
}
// Process form submission
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Retrieve form data
$question1 = $_POST['question1'];
$question2 = $_POST['question2'];
// Perform calculations
$total = $question1 + $question2;
// Store data in the database
$sql = "INSERT INTO survey_responses (question1, question2, total) VALUES ('$question1', '$question2', '$total')";
if ($conn->query($sql) === TRUE) {
echo "Survey response recorded successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
// Close database connection
$conn->close();
?>
Related Questions
- What potential pitfalls should be avoided when using the PHP mail function to send emails?
- What are the best practices for managing session variables in PHP when register_globals is off?
- What are the differences between using array_values and reset/next functions to extract values from a filtered array in PHP?