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

PHP实现多复选框数据读取及跨表插入的技术咨询

Got it, let's fix up your code and implement the full feature step by step. Here's a complete, secure solution that addresses your requirements, with fixes for deprecated functions and proper security practices:

Complete Solution: Display Test Data with Checkboxes & Insert Selected Rows to Package Table

First, note the issues in your initial code: you're mixing deprecated mysql_* functions with modern mysqli_* functions, which won't work. We'll use pure mysqli and add proper security measures to avoid SQL injection and XSS attacks.

Step 1: PHP Backend (Connection, Data Fetch & Submission Handling)

This snippet handles database connection, fetches data from the test table, and processes the form submission to insert selected rows into the package table.

<?php
// Establish secure database connection
$conn = mysqli_connect("localhost", "root", "", "laboratory") or die("Connection failed: " . mysqli_connect_error());

// Handle form submission: insert selected rows into package table
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['selected_ids'])) {
    // Sanitize selected IDs to prevent SQL injection (only allow integers)
    $selectedIds = array_map('intval', $_POST['selected_ids']);
    
    if (!empty($selectedIds)) {
        // Adjust column names here to match your `package` table structure
        // Example: if package has columns id, name, value, use those instead
        $insertQuery = "INSERT INTO package (id, column1, column2, column3)
                      SELECT id, column1, column2, column3 FROM test WHERE id IN (" . implode(',', $selectedIds) . ")";
        
        if (mysqli_query($conn, $insertQuery)) {
            $successMsg = "Success! Inserted " . mysqli_affected_rows($conn) . " rows into the package table.";
        } else {
            $errorMsg = "Insert failed: " . mysqli_error($conn);
        }
    } else {
        $errorMsg = "Please select at least one row to insert.";
    }
}

// Fetch data from test table
$query = "SELECT * FROM test";
$result = mysqli_query($conn, $query);
?>

Step 2: HTML Frontend (Table with Checkboxes & Form)

This part creates an interactive table with checkboxes for each row, plus feedback messages for success/errors.

<!DOCTYPE html>
<html>
<head>
    <title>Test Data to Package</title>
    <style>
        table { border-collapse: collapse; width: 90%; margin: 2rem auto; }
        th, td { border: 1px solid #eee; padding: 0.8rem; text-align: left; }
        th { background-color: #f5f5f5; }
        .message { padding: 1rem; width: 90%; margin: 1rem auto; border-radius: 4px; }
        .success { background-color: #d4edda; color: #155724; }
        .error { background-color: #f8d7da; color: #721c24; }
        .submit-btn { display: block; margin: 0 auto 2rem; padding: 0.8rem 1.5rem; cursor: pointer; }
    </style>
</head>
<body>
    <h2 style="text-align:center;">Test Table Data</h2>

    <!-- Display feedback messages -->
    <?php if (isset($successMsg)): ?>
        <div class="message success"><?php echo $successMsg; ?></div>
    <?php endif; ?>
    <?php if (isset($errorMsg)): ?>
        <div class="message error"><?php echo $errorMsg; ?></div>
    <?php endif; ?>

    <!-- Form to submit selected rows -->
    <form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
        <table>
            <tr>
                <th>Select</th>
                <!-- Dynamically generate table headers from test table columns -->
                <?php while ($column = mysqli_fetch_field($result)): ?>
                    <th><?php echo $column->name; ?></th>
                <?php endwhile; ?>
            </tr>
            <?php 
            // Reset result pointer to fetch rows after getting headers
            mysqli_data_seek($result, 0);
            while ($record = mysqli_fetch_assoc($result)): 
            ?>
            <tr>
                <td><input type="checkbox" name="selected_ids[]" value="<?php echo $record['id']; ?>"></td>
                <!-- Dynamically display each row's data -->
                <?php foreach ($record as $value): ?>
                    <td><?php echo htmlspecialchars($value); ?></td>
                <?php endforeach; ?>
            </tr>
            <?php endwhile; ?>
        </table>
        <button type="submit" class="submit-btn">Insert Selected Rows to Package</button>
    </form>
</body>
</html>

<?php
// Clean up: close database connection
mysqli_close($conn);
?>

Key Improvements & Notes:

  • Security: Uses htmlspecialchars() to prevent XSS attacks when displaying data, and intval() to sanitize selected IDs (safe for integer primary keys). For non-integer keys, use prepared statements with placeholders instead.
  • Dynamic Layout: Table headers and rows are generated automatically based on your test table structure, so you don’t need to hardcode columns if your table changes.
  • Error Handling: Provides clear feedback for connection issues, empty selections, and query failures.
  • Deprecated Functions: Removed all unsupported mysql_* functions to ensure compatibility with modern PHP versions.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:48:52