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

动态HTML表单数组数据PHP入库失败,寻求解决方法

Hey there, let's fix this step by step — I see a few key issues that are stopping your data from inserting correctly.

1. Mismatched Field Names (Case Sensitivity)

Your HTML/JS uses otherName[] and lastName[], but in PHP you're trying to access $_POST["othername"] and $_POST["lastname"]. PHP array keys are case-sensitive, so these don't match! That means those arrays are actually empty in your PHP code right now.

2. Broken Loop Syntax

Your for loop syntax is invalid — you can't chain multiple initializations/conditions like that. Since each row has one name, one otherName, and one lastName, all three arrays should have the same length. So you just need a single loop index to iterate through all three arrays together.

3. Incorrect Trim Placement

Your condition trim($_POST["name"][$i] != '') is trimming the result of the comparison, not the actual input value. You need to trim the input first, then check if it's not empty.

4. (Bonus) Better SQL Security

While mysqli_real_escape_string helps, using prepared statements is safer and cleaner for preventing SQL injection.


First, Fix the HTML/JS Field Names (Match PHP Case)

Update the JS append code to use lowercase consistent with your PHP (or adjust PHP to match JS — just keep them consistent):

$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><input type="text" name="othername[]" placeholder="Enter your Other Name" class="form-control name_last" /></td><td><input type="text" name="lastname[]" placeholder="Enter your Last Name" class="form-control name_last" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');

Fixed PHP Code

<?php
$connect = mysqli_connect("localhost", "root", "", "testing");

// Check if all required arrays exist and have matching lengths
if(isset($_POST["name"], $_POST["othername"], $_POST["lastname"]) && 
   count($_POST["name"]) === count($_POST["othername"]) && 
   count($_POST["name"]) === count($_POST["lastname"])) {

    $number = count($_POST["name"]);
    $inserted = false;

    // Use prepared statement to avoid SQL injection
    $stmt = mysqli_prepare($connect, "INSERT INTO bl_name (name, othername, lastname) VALUES (?, ?, ?)");
    mysqli_stmt_bind_param($stmt, "sss", $name, $othername, $lastname);

    for($i = 0; $i < $number; $i++){
        // Trim inputs and check if they're not empty
        $name = trim($_POST["name"][$i]);
        $othername = trim($_POST["othername"][$i]);
        $lastname = trim($_POST["lastname"][$i]);

        if(!empty($name) && !empty($othername) && !empty($lastname)){
            mysqli_stmt_execute($stmt);
            $inserted = true;
        }
    }

    mysqli_stmt_close($stmt);
    mysqli_close($connect);

    echo $inserted ? "Data Inserted Successfully" : "Please Enter Valid Data for at Least One Row";
} else {
    echo "Invalid Data Submitted or Mismatched Field Counts";
}
?>

Key Fixes Explained:

  • Consistent Naming: Now othername[] and lastname[] are used across HTML/JS/PHP, so PHP can actually access the submitted values.
  • Single Index Loop: We use one index $i to grab the corresponding values from all three arrays (since each row adds one entry to each array).
  • Proper Input Validation: We trim each input first, then check if it's non-empty to avoid inserting blank rows.
  • Prepared Statements: This is a more secure way to handle SQL inserts, eliminating the risk of SQL injection entirely.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:01:41