PHP LogoSurvey Creation Application

A Survey Creation Application is a software tool that enables users to design, distribute, and analyze surveys. These applications are vital for gathering feedback, conducting market research, academic studies, or simply polling opinions. The core idea is to provide an intuitive interface for creating surveys and a robust backend for collecting and presenting data.

Key Features:

1. Survey Management: Users (typically administrators or survey creators) can create new surveys, give them titles and descriptions, and set various parameters like start/end dates, visibility, and target audience.
2. Question Design: The application allows for adding different types of questions, such as:
* Multiple Choice: Participants select one option from a predefined list.
* Checkboxes: Participants can select multiple options from a list.
* Open-ended/Text Input: Participants provide free-form text answers.
* Rating Scales: Participants rate items on a scale (e.g., Likert scale).
* Dropdowns: Similar to multiple choice but presented as a dropdown menu.
3. Response Collection: The application provides a mechanism for participants to access and answer the surveys. This often involves unique survey URLs or embedding options.
4. Data Storage: All survey structures (questions, choices) and participant responses are stored persistently, typically in a relational database (like MySQL or PostgreSQL).
5. Reporting and Analysis: After responses are collected, the application generates reports, charts, and statistics to help creators understand the data. This might include response counts, percentages for multiple-choice questions, and tools for reviewing text-based answers.
6. User Authentication & Authorization (Optional but Common): Differentiating between survey creators, administrators, and participants, potentially with different levels of access and permissions.

Technology Stack (Example using PHP):

* Frontend (User Interface): HTML for structuring the content, CSS for styling, and JavaScript for client-side interactivity, validation, and dynamic updates.
* Backend (Server-Side Logic): PHP handles requests from the client, interacts with the database, processes form submissions, manages session data, and serves dynamic content.
* Database: MySQL or PostgreSQL is commonly used to store:
* `surveys` table (survey ID, title, description, creation date)
* `questions` table (question ID, survey ID, question text, type)
* `choices` table (choice ID, question ID, choice text)
* `responses` table (response ID, survey ID, participant ID, timestamp)
* `answers` table (answer ID, response ID, question ID, chosen choice ID/text answer)

Typical Workflow:

1. A user logs in as a survey creator.
2. They navigate to a 'Create New Survey' section.
3. They input the survey title and description.
4. They add questions, specifying the type and possible answer choices for each.
5. The survey is saved to the database.
6. The creator shares the survey link with participants.
7. Participants visit the link, answer the questions, and submit their responses.
8. The PHP backend receives the submitted data, validates it, and stores it in the `responses` and `answers` tables.
9. The creator can then access a 'View Results' section, where PHP queries the database to aggregate and display the survey data, often visualized with charts generated by JavaScript libraries.

Example Code

```php
<?php

// This is a simplified example demonstrating a single survey and vote processing.
// In a real application, survey data, questions, and responses would be stored in a database.

// --- Survey Data (simulated from a database) ---
$survey_id = 1;
$survey_title = "Favorite Programming Language Survey";
$questions = [
    [
        'id' => 101,
        'text' => 'Which programming language do you prefer for web development?',
        'type' => 'radio',
        'options' => [
            ['id' => 1001, 'text' => 'PHP'],
            ['id' => 1002, 'text' => 'Python'],
            ['id' => 1003, 'text' => 'JavaScript (Node.js)'],
            ['id' => 1004, 'text' => 'Ruby'],
            ['id' => 1005, 'text' => 'Java']
        ]
    ],
    [
        'id' => 102,
        'text' => 'What other languages do you use regularly? (Select all that apply)',
        'type' => 'checkbox',
        'options' => [
            ['id' => 2001, 'text' => 'C#'],
            ['id' => 2002, 'text' => 'C++'],
            ['id' => 2003, 'text' => 'Go'],
            ['id' => 2004, 'text' => 'Swift'],
            ['id' => 2005, 'text' => 'Kotlin']
        ]
    ],
    [
        'id' => 103,
        'text' => 'Any additional comments on your language preferences?',
        'type' => 'textarea'
    ]
];

// --- Response Storage (simulated with a session for demonstration) ---
// In a real application, this would be stored in a database.
session_start();

if (!isset($_SESSION['survey_responses'][$survey_id])) {
    $_SESSION['survey_responses'][$survey_id] = [];
}

// --- Handle Form Submission ---
$message = '';
$has_voted = false;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_survey'])) {
    $response = [
        'timestamp' => date('Y-m-d H:i:s'),
        'answers' => []
    ];

    foreach ($questions as $question) {
        $question_id = $question['id'];
        $answer_key = 'q_' . $question_id;

        if ($question['type'] === 'radio' && isset($_POST[$answer_key])) {
            $selected_option_id = (int)$_POST[$answer_key];
            // Find the text of the selected option
            $selected_text = '';
            foreach ($question['options'] as $option) {
                if ($option['id'] === $selected_option_id) {
                    $selected_text = $option['text'];
                    break;
                }
            }
            $response['answers'][$question_id] = ['type' => 'radio', 'value' => $selected_option_id, 'text' => $selected_text];
        } elseif ($question['type'] === 'checkbox' && isset($_POST[$answer_key]) && is_array($_POST[$answer_key])) {
            $selected_option_ids = array_map('intval', $_POST[$answer_key]);
            $selected_texts = [];
            foreach ($question['options'] as $option) {
                if (in_array($option['id'], $selected_option_ids)) {
                    $selected_texts[] = $option['text'];
                }
            }
            $response['answers'][$question_id] = ['type' => 'checkbox', 'value' => $selected_option_ids, 'text' => $selected_texts];
        } elseif ($question['type'] === 'textarea' && isset($_POST[$answer_key])) {
            $response['answers'][$question_id] = ['type' => 'textarea', 'value' => htmlspecialchars(trim($_POST[$answer_key]))];
        }
    }

    // Add the response to our simulated storage
    $_SESSION['survey_responses'][$survey_id][] = $response;
    $message = "Thank you for your response!";
    $has_voted = true;
    // In a real app, you might redirect to a 'thank you' page
}

// --- Prepare Results for Display ---
$total_responses = count($_SESSION['survey_responses'][$survey_id]);
$results = [];

foreach ($questions as $question) {
    $q_id = $question['id'];
    $results[$q_id] = [
        'text' => $question['text'],
        'type' => $question['type'],
        'data' => []
    ];

    if ($question['type'] === 'radio' || $question['type'] === 'checkbox') {
        foreach ($question['options'] as $option) {
            $results[$q_id]['data'][$option['id']] = ['text' => $option['text'], 'count' => 0];
        }
    }
}

foreach ($_SESSION['survey_responses'][$survey_id] as $response) {
    foreach ($response['answers'] as $q_id => $answer) {
        // Find the question type dynamically
        $question_type = null;
        foreach($questions as $q) {
            if ($q['id'] === $q_id) {
                $question_type = $q['type'];
                break;
            }
        }

        if ($question_type === 'radio') {
            if (isset($results[$q_id]['data'][$answer['value']])) {
                $results[$q_id]['data'][$answer['value']]['count']++;
            }
        } elseif ($question_type === 'checkbox') {
            foreach ($answer['value'] as $option_id) {
                if (isset($results[$q_id]['data'][$option_id])) {
                    $results[$q_id]['data'][$option_id]['count']++;
                }
            }
        } elseif ($question_type === 'textarea') {
            $results[$q_id]['data'][] = $answer['value']; // Store individual text answers
        }
    }
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($survey_title); ?></title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
        .container { max-width: 800px; margin: auto; background: #fff; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1, h2 { color: #0056b3; }
        .question-block { margin-bottom: 25px; padding: 15px; border: 1px solid #eee; border-radius: 5px; background-color: #f9f9f9; }
        .question-block label { display: block; margin-bottom: 8px; font-weight: bold; }
        .option-group label { display: block; margin-bottom: 5px; font-weight: normal; }
        input[type="radio"], input[type="checkbox"] { margin-right: 8px; }
        textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; min-height: 80px; }
        button { background-color: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin-top: 10px; }
        button:hover { background-color: #0056b3; }
        .message { padding: 10px; margin-bottom: 20px; border-radius: 5px; background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
        .results-section { margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; }
        .results-item { margin-bottom: 20px; }
        .results-item ul { list-style: none; padding: 0; }
        .results-item li { background-color: #e9ecef; margin-bottom: 5px; padding: 8px 12px; border-radius: 4px; display: flex; justify-content: space-between; align-items: center; }
        .results-item li span:first-child { flex-grow: 1; }
        .results-item li span:last-child { font-weight: bold; color: #007bff; }
        .total-responses { font-weight: bold; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <h1><?php echo htmlspecialchars($survey_title); ?></h1>

        <?php if ($message): ?>
            <div class="message"><?php echo $message; ?></div>
        <?php endif; ?>

        <?php if (!$has_voted): // Show form if not voted ?>
            <form method="POST" action="">
                <?php foreach ($questions as $question): ?>
                    <div class="question-block">
                        <label><?php echo htmlspecialchars($question['text']); ?></label>
                        <?php if ($question['type'] === 'radio'): ?>
                            <div class="option-group">
                                <?php foreach ($question['options'] as $option): ?>
                                    <label>
                                        <input type="radio" name="q_<?php echo $question['id']; ?>" value="<?php echo $option['id']; ?>" required>
                                        <?php echo htmlspecialchars($option['text']); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        <?php elseif ($question['type'] === 'checkbox'): ?>
                            <div class="option-group">
                                <?php foreach ($question['options'] as $option): ?>
                                    <label>
                                        <input type="checkbox" name="q_<?php echo $question['id']; ?>[]" value="<?php echo $option['id']; ?>">
                                        <?php echo htmlspecialchars($option['text']); ?>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        <?php elseif ($question['type'] === 'textarea'): ?>
                            <textarea name="q_<?php echo $question['id']; ?>" placeholder="Your comments..."></textarea>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
                <button type="submit" name="submit_survey">Submit Survey</button>
            </form>
        <?php endif; ?>

        <div class="results-section">
            <h2>Survey Results</h2>
            <p class="total-responses">Total Responses: <?php echo $total_responses; ?></p>

            <?php foreach ($results as $q_id => $q_result): ?>
                <div class="results-item">
                    <h3><?php echo htmlspecialchars($q_result['text']); ?></h3>
                    <?php if ($q_result['type'] === 'radio' || $q_result['type'] === 'checkbox'): ?>
                        <ul>
                            <?php foreach ($q_result['data'] as $option_id => $option_data): ?>
                                <li>
                                    <span><?php echo htmlspecialchars($option_data['text']); ?></span>
                                    <span><?php echo $option_data['count']; ?> votes (<?php echo $total_responses > 0 ? round(($option_data['count'] / $total_responses) * 100, 2) : 0; ?>%)</span>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                    <?php elseif ($q_result['type'] === 'textarea'): ?>
                        <p>Text answers:</p>
                        <ul>
                            <?php if (empty($q_result['data'])): ?>
                                <li>No text answers yet.</li>
                            <?php else: ?>
                                <?php foreach ($q_result['data'] as $text_answer): ?>
                                    <li>"<?php echo htmlspecialchars($text_answer); ?>"</li>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </ul>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>

    </div>
</body>
</html>
```