Skip to content
PHP Logo

What techniques or methods can be used in PHP to generate dynamic survey pages for users to fill out?

To generate dynamic survey pages in PHP, you can use a combination of HTML forms and PHP scripting to create a form that dynamically generates questions based on a dataset or predefined questions. You can use arrays or databases to store the questions and their corresponding input types, and loop through them to display the form elements on the page.

php
<?php
// Define an array of survey questions
$surveyQuestions = array(
    "What is your age?" => "text",
    "How satisfied are you with our service?" => "radio",
    "Would you recommend us to a friend?" => "checkbox"
);

// Generate the survey form dynamically
echo '<form method="post">';
foreach ($surveyQuestions as $question => $inputType) {
    echo '<label>' . $question . '</label><br>';
    if ($inputType == "text") {
        echo '<input type="text" name="' . str_replace(' ', '_', $question) . '"><br>';
    } elseif ($inputType == "radio") {
        echo '<input type="radio" name="' . str_replace(' ', '_', $question) . '" value="satisfied">Satisfied';
        echo '<input type="radio" name="' . str_replace(' ', '_', $question) . '" value="neutral">Neutral';
        echo '<input type="radio" name="' . str_replace(' ', '_', $question) . '" value="dissatisfied">Dissatisfied<br>';
    } elseif ($inputType == "checkbox") {
        echo '<input type="checkbox" name="' . str_replace(' ', '_', $question) . '[]" value="yes">Yes<br>';
    }
}
echo '<input type="submit" value="Submit">';
echo '</form>';
?>