In the context of online surveys, what are the potential risks of inserting data into the database after each question is answered?

Inserting data into the database after each question is answered can lead to performance issues, as it requires multiple database operations for each question. This can slow down the survey process and potentially overload the database server. To solve this issue, it is better to collect all the survey responses in memory and then insert them into the database in a single transaction after the survey is completed.

// Collect survey responses in an array
$responses = array(
    'question1' => $_POST['question1'],
    'question2' => $_POST['question2'],
    'question3' => $_POST['question3'],
    // Add more questions as needed
);

// Insert survey responses into the database in a single transaction
try {
    $pdo = new PDO('mysql:host=localhost;dbname=survey_db', 'username', 'password');
    $pdo->beginTransaction();

    $stmt = $pdo->prepare("INSERT INTO survey_responses (question, response) VALUES (:question, :response)");

    foreach ($responses as $question => $response) {
        $stmt->bindParam(':question', $question);
        $stmt->bindParam(':response', $response);
        $stmt->execute();
    }

    $pdo->commit();
} catch (PDOException $e) {
    $pdo->rollBack();
    echo "Error: " . $e->getMessage();
}