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$rdinamearen'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
$data1array has duplicate keys (vfstock,hfstockrepeated 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
$data1three times. If you need different values per iteration, you need to adjust$data1inside the loop. - Missing Input Handling: You're not retrieving values like
tfstank1-tfstank5from 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
- Defined All Variables: Added retrieval of missing POST values and defined
$rdiname(adjust this if it's a separate POST field). - Removed Duplicate Keys: Redefined
$data1with unique keys, using dynamic variable access to assign differenttfstankvalues per loop iteration. - 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. - Error Checking: Added a check to ensure the first insert succeeds before running the loop. Update your model methods to return
true/falsebased on insert success. - Dynamic Value Handling: Used
${'tfstank' . $i}to dynamically access the correcttfstankvariable 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
相关产品推荐
相关产品推荐

