You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP&MySQLi实现单选按钮切换注册表单并入库的技术咨询

Solution for Toggleable Student/College Registration Form with PHP & MySQLi

Got it, let's walk through how to implement this step by step. We'll cover the frontend toggle logic, database setup, and secure backend handling.

1. Frontend: HTML & JavaScript for Form Toggling

First, let's fix your existing radio buttons (IDs must be unique!) and add the two registration form sections. We'll wrap everything in a single <form> tag so we can submit all data at once.

Full HTML Code

<?php include 'register.php'; // Include our backend logic ?>

<!DOCTYPE html>
<html>
<head>
    <title>Registration</title>
    <style>
        .registration-form {
            margin-top: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .error { color: red; }
        .success { color: green; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Register as College or Student</h2>

        <!-- Display Success/Error Messages -->
        <?php if (!empty($error)): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        <?php if (!empty($success)): ?>
            <div class="success"><?php echo $success; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <!-- Radio Buttons -->
            <div class="col-lg-6">
                <h5>Are you a College or Student?</h5>
                <div class="form-group form-check-inline">
                    <label class="custom-control custom-radio">
                        <input id="college_radio" name="radio" value="0" type="radio" class="custom-control-input">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">College</span>
                    </label>
                </div>
                <div class="form-group form-check-inline">
                    <label class="custom-control custom-radio">
                        <input id="student_radio" name="radio" value="1" type="radio" class="custom-control-input">
                        <span class="custom-control-indicator"></span>
                        <span class="custom-control-description">Student</span>
                    </label>
                </div>
            </div>

            <!-- College Registration Form -->
            <div id="college_form" class="registration-form">
                <h3>College Details</h3>
                <div class="form-group">
                    <label>College Name:</label>
                    <input type="text" name="college_name" class="form-control" value="<?php echo isset($_POST['college_name']) ? htmlspecialchars($_POST['college_name']) : ''; ?>">
                </div>
                <div class="form-group">
                    <label>Address:</label>
                    <textarea name="college_address" class="form-control"><?php echo isset($_POST['college_address']) ? htmlspecialchars($_POST['college_address']) : ''; ?></textarea>
                </div>
                <div class="form-group">
                    <label>Contact Number:</label>
                    <input type="text" name="college_contact" class="form-control" value="<?php echo isset($_POST['college_contact']) ? htmlspecialchars($_POST['college_contact']) : ''; ?>">
                </div>
            </div>

            <!-- Student Registration Form -->
            <div id="student_form" class="registration-form" style="display:none;">
                <h3>Student Details</h3>
                <div class="form-group">
                    <label>Full Name:</label>
                    <input type="text" name="student_name" class="form-control" value="<?php echo isset($_POST['student_name']) ? htmlspecialchars($_POST['student_name']) : ''; ?>">
                </div>
                <div class="form-group">
                    <label>Email:</label>
                    <input type="email" name="student_email" class="form-control" value="<?php echo isset($_POST['student_email']) ? htmlspecialchars($_POST['student_email']) : ''; ?>">
                </div>
                <div class="form-group">
                    <label>Phone Number:</label>
                    <input type="text" name="student_phone" class="form-control" value="<?php echo isset($_POST['student_phone']) ? htmlspecialchars($_POST['student_phone']) : ''; ?>">
                </div>
            </div>

            <button type="submit" class="btn btn-primary" style="margin-top:15px;">Register</button>
        </form>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const radioButtons = document.querySelectorAll('input[name="radio"]');
            const collegeForm = document.getElementById('college_form');
            const studentForm = document.getElementById('student_form');

            // Set initial form visibility (preserve state after submission)
            const selectedType = <?php echo isset($_POST['radio']) ? (int)$_POST['radio'] : 0; ?>;
            if (selectedType === 0) {
                collegeForm.style.display = 'block';
                studentForm.style.display = 'none';
                document.getElementById('college_radio').checked = true;
            } else {
                collegeForm.style.display = 'none';
                studentForm.style.display = 'block';
                document.getElementById('student_radio').checked = true;
            }

            // Toggle form on radio change
            function toggleForm() {
                if (this.value === '0') {
                    collegeForm.style.display = 'block';
                    studentForm.style.display = 'none';
                } else {
                    collegeForm.style.display = 'none';
                    studentForm.style.display = 'block';
                }
            }

            radioButtons.forEach(radio => radio.addEventListener('change', toggleForm));
        });
    </script>
</body>
</html>

2. Database Setup

Create a MySQL table to store the registration data. We'll use a single table with nullable columns (since college and student fields don't overlap much). Run this query in your MySQL client:

CREATE TABLE registrations (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_type INT NOT NULL COMMENT '0 = College, 1 = Student',
    -- College fields
    college_name VARCHAR(255) NULL,
    college_address TEXT NULL,
    college_contact VARCHAR(50) NULL,
    -- Student fields
    student_name VARCHAR(255) NULL,
    student_email VARCHAR(255) NULL,
    student_phone VARCHAR(50) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

3. Backend: PHP & MySQLi Handling

Create a file named register.php (the one we included in the HTML) to handle form submission, validation, and database insertion. We'll use prepared statements to prevent SQL injection.

<?php
// Database configuration (update these with your credentials)
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_db_username';
$password = 'your_db_password';

// Initialize connection
$conn = new mysqli($host, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get and validate user type
    $user_type = isset($_POST['radio']) ? (int)$_POST['radio'] : -1;
    if (!in_array($user_type, [0, 1])) {
        $error = 'Please select whether you are a College or Student.';
    } else {
        if ($user_type === 0) {
            // Process College Registration
            $college_name = trim($_POST['college_name'] ?? '');
            $college_address = trim($_POST['college_address'] ?? '');
            $college_contact = trim($_POST['college_contact'] ?? '');

            // Validate college fields
            if (empty($college_name) || empty($college_address) || empty($college_contact)) {
                $error = 'Please fill in all College fields.';
            } else {
                // Insert into database using prepared statement
                $stmt = $conn->prepare("INSERT INTO registrations (user_type, college_name, college_address, college_contact) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isss", $user_type, $college_name, $college_address, $college_contact);

                if ($stmt->execute()) {
                    $success = 'College registration completed successfully!';
                } else {
                    $error = 'Error: ' . $stmt->error;
                }
                $stmt->close();
            }
        } else {
            // Process Student Registration
            $student_name = trim($_POST['student_name'] ?? '');
            $student_email = trim($_POST['student_email'] ?? '');
            $student_phone = trim($_POST['student_phone'] ?? '');

            // Validate student fields (including email format)
            if (empty($student_name) || empty($student_email) || !filter_var($student_email, FILTER_VALIDATE_EMAIL) || empty($student_phone)) {
                $error = 'Please fill in all Student fields correctly (valid email required).';
            } else {
                // Insert into database using prepared statement
                $stmt = $conn->prepare("INSERT INTO registrations (user_type, student_name, student_email, student_phone) VALUES (?, ?, ?, ?)");
                $stmt->bind_param("isss", $user_type, $student_name, $student_email, $student_phone);

                if ($stmt->execute()) {
                    $success = 'Student registration completed successfully!';
                } else {
                    $error = 'Error: ' . $stmt->error;
                }
                $stmt->close();
            }
        }
    }
}

// Close connection
$conn->close();
?>

Key Notes & Best Practices

  • Security: We use prepared statements to avoid SQL injection, and htmlspecialchars() to prevent XSS attacks when displaying user input.
  • Validation: Always validate user input on the backend (frontend validation is optional but recommended for better UX).
  • Alternative Database Structure: If college and student data have many unique fields, consider using separate tables (colleges and students) linked to a main users table with user_type.
  • UX: The JavaScript preserves the selected form state after submission, so users don't lose their progress if there's an error.

内容的提问来源于stack exchange,提问作者user9515089

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:44:27