What are the potential pitfalls of using nested MySQL queries in PHP to retrieve survey data?
Using nested MySQL queries in PHP to retrieve survey data can lead to performance issues, as each nested query requires additional database calls. To avoid this, it is recommended to use JOIN statements in the initial query to retrieve all necessary data in a single query. This will reduce the number of database calls and improve the overall performance of the application.
// Using JOIN statements to retrieve survey data
$query = "SELECT surveys.id, surveys.title, questions.question_text, answers.answer_text
FROM surveys
JOIN questions ON surveys.id = questions.survey_id
JOIN answers ON questions.id = answers.question_id
WHERE surveys.id = :survey_id";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':survey_id', $survey_id);
$stmt->execute();
// Fetching and displaying survey data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "Survey ID: " . $row['id'] . "<br>";
echo "Survey Title: " . $row['title'] . "<br>";
echo "Question: " . $row['question_text'] . "<br>";
echo "Answer: " . $row['answer_text'] . "<br><br>";
}