What is the best practice for storing and retrieving dynamic survey data in a PHP database?
Storing and retrieving dynamic survey data in a PHP database requires creating a flexible database structure to accommodate varying survey questions and responses. One approach is to use a relational database with tables for surveys, questions, and responses, allowing for dynamic creation and storage of survey data. To retrieve the data, you can use SQL queries to fetch specific survey responses based on survey identifiers.
// Example of storing survey data in a MySQL database
// Connect to 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);
}
// Insert survey response into database
$survey_id = 1; // ID of the survey
$question_id = 1; // ID of the question
$response = "Example response";
$sql = "INSERT INTO survey_responses (survey_id, question_id, response) VALUES ($survey_id, $question_id, '$response')";
if ($conn->query($sql) === TRUE) {
echo "Survey response stored successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
// Retrieve survey responses from database
$survey_id = 1; // ID of the survey to retrieve responses for
$sql = "SELECT * FROM survey_responses WHERE survey_id = $survey_id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Question ID: " . $row["question_id"]. " - Response: " . $row["response"]. "<br>";
}
} else {
echo "No survey responses found";
}
$conn->close();
Related Questions
- What is the difference between number_format and round functions in PHP?
- How can the use of placeholders and prepared statements in PHP improve the security and efficiency of database update operations?
- What are some best practices for securely including files in PHP applications to prevent vulnerabilities?