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

CodeIgniter双表插入异常:单表单次插入正常,循环插3次失败求助

Troubleshooting Your CodeIgniter Insert Loop Issue

Hey Amit, let's break down why your loop isn't working and fix those issues step by step. Here are the main problems in your code:

  • Undefined Variables: Variables like $gtfb, $tfstank1, $tfstank2, and $rdiname aren't defined anywhere in your function. PHP will throw fatal errors here, which likely halt execution before the loop even starts.
  • Duplicate Array Keys: Your $data1 array has duplicate keys (vfstock, hfstock repeated multiple times). In PHP, duplicate keys overwrite each other, so only the last value for each key will be stored—this is almost certainly not what you intended.
  • Loop Inserts Identical Data: Even if the loop ran, it would insert the exact same $data1 three times. If you need different values per iteration, you need to adjust $data1 inside the loop.
  • Missing Input Handling: You're not retrieving values like tfstank1-tfstank5 from the POST data, which is why those variables are undefined.

Fixed Code with Explanations

I'll assume you're receiving tfstank1 to tfstank5 via POST, and that you want to insert different vfstock/hfstock values in each loop iteration (adjust as needed based on your actual requirements):

public function add_rdi() {
    // Retrieve all necessary POST data
    $user_id = $this->input->post('user_id');
    $user_rdi = $this->input->post('user_rdi');
    $zoneID = $this->input->post('zoneID');
    $mtstock6 = $this->input->post('mtstock6');
    $tfstank6 = $this->input->post('tfstank6');
    // Add missing POST variables (adjust field names if they differ)
    $gtfb = $this->input->post('gtfb');
    $tfstank1 = $this->input->post('tfstank1');
    $tfstank2 = $this->input->post('tfstank2');
    $tfstank3 = $this->input->post('tfstank3');
    $tfstank4 = $this->input->post('tfstank4');
    $tfstank5 = $this->input->post('tfstank5');
    $rdiname = $user_rdi; // Assuming rdiname matches user_rdi; adjust if needed

    $this->load->model('Mechanical_model_rdi');

    // Check if RDI exists before proceeding
    $query = $this->db->where('rdiname', $rdiname)->get('fuel_rdi');
    if ($query->num_rows() < 1) {
        // Insert into table1 (your original single entry)
        $data = [
            'user_id' => $user_id,
            'user_rdi' => $user_rdi,
            'zoneID' => $zoneID,
            'mtstock6' => $mtstock6,
            'tfstank6' => $tfstank6,
        ];
        $first_insert_success = $this->Mechanical_model_rdi->add_rdi_table1($data);

        // Only run loop if first insert succeeds
        if ($first_insert_success) {
            // Loop to insert 3 distinct entries into table2
            for ($i = 1; $i <= 3; $i++) {
                // Assign appropriate tfstank value based on loop index
                $vfstock = ${'tfstank' . $i}; // Dynamically get tfstank1, tfstank2, tfstank3
                $hfstock = ($i <= 3) ? ${'tfstank' . ($i + 3)} : null; // Gets tfstank4, tfstank5, tfstank6

                $data1 = [
                    'fuelstock' => $gtfb,
                    'fuelrecrdi' => $gtfb,
                    'stockrdiname' => $user_rdi,
                    'vfstock' => $vfstock,
                    'hfstock' => $hfstock,
                    'user_id' => $user_id
                ];

                // Insert into table2 (use a dedicated model method)
                $this->Mechanical_model_rdi->add_rdi_table2($data1);
            }
        }
    }

    $this->load->view('mechanical/Mechanical_add_rdi');
}

Key Fixes Explained

  1. Defined All Variables: Added retrieval of missing POST values and defined $rdiname (adjust this if it's a separate POST field).
  2. Removed Duplicate Keys: Redefined $data1 with unique keys, using dynamic variable access to assign different tfstank values per loop iteration.
  3. Separate Model Methods: Created distinct methods (add_rdi_table1, add_rdi_table2) for each table to keep your code clean and avoid confusion. You'll need to implement these in your model to target the correct tables.
  4. Error Checking: Added a check to ensure the first insert succeeds before running the loop. Update your model methods to return true/false based on insert success.
  5. Dynamic Value Handling: Used ${'tfstank' . $i} to dynamically access the correct tfstank variable for each loop iteration, making the code scalable.

Additional Recommendations

  • Enable Error Reporting: In CodeIgniter's config.php, set $config['log_threshold'] = 2; to see detailed error logs—this will help you catch undefined variables or database issues quickly.
  • Transaction Handling: Wrap your inserts in a database transaction to ensure all operations succeed or fail together, preventing partial data insertion:
    $this->db->trans_start();
    // Run all insert queries here
    $this->db->trans_complete();
    
    if ($this->db->trans_status() === FALSE) {
        // Handle failure (e.g., show error message to user)
    }
    
  • Input Validation: Add CodeIgniter's form validation to ensure all required POST fields are present and valid before processing inserts.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:00:22