Codeigniter CSV导入数据:关联表ID获取与插入错误修复求助
Looking at your code, the main issue is how you're retrieving and using the pid value from the or_peserta table. Let's break down the problems and fix them step by step:
1. Model: Return the Actual ID Value, Not a Result Set
Your getid() method currently returns $query->result(), which gives you an array of objects (even if there's only one matching row). This means $pid in your controller is an array/object instead of the integer ID you need. Let's adjust the model to return the single ID value:
function getid($nip) { $this->db->select('id'); $this->db->from('or_peserta'); $this->db->where('nip', $nip); $query = $this->db->get(); // Check if a matching row exists if ($query->num_rows() > 0) { // Return the actual ID from the first matching row return $query->row()->id; } else { // Return null if no match is found (handle this in the controller) return null; } }
2. Controller: Initialize the Insert Array and Validate IDs
In your controller, you need to:
- Initialize the insert array to avoid undefined variable errors
- Skip rows where no matching
pidwas found (to avoid inserting invalid data) - Only run the batch insert if there are valid rows to insert
Here's the corrected controller code:
function imports($aid) { // Initialize the insert array to prevent undefined variable issues $insertData = []; // Get CSV data (skip header row with array_slice) $fileData = $this->csvimport->get_array($_FILES["csv_file"]["tmp_name"]); foreach(array_slice($fileData, 1) as $row) { $pid = $this->m_csvimport->getid($row["nip"]); // Only add to insert array if we found a valid pid if ($pid !== null) { $insertData[] = [ 'aid' => $aid, 'pid' => $pid, 'kodeunik' => '', ]; } else { // Optional: Log a warning for rows with invalid nip log_message('warning', "No matching peserta found for NIP: " . $row["nip"]); } } // Only perform the batch insert if there's valid data if (!empty($insertData)) { $this->m_csvimport->inserts($insertData); // Optional: Add success message or redirect here // $this->session->set_flashdata('success', 'Data imported successfully!'); // redirect('your-controller/your-method'); } else { // Optional: Handle case where no valid rows were found log_message('info', "No valid rows to import from CSV"); // $this->session->set_flashdata('error', 'No valid data found in CSV'); // redirect('your-controller/import-form'); } }
3. Model: Inserts Method (Minor Improvement)
Your inserts() method is fine, but adding a check for empty input can prevent unnecessary database calls:
function inserts($array) { if (!empty($array)) { $this->db->insert_batch('or_tr_pa', $array); // Optional: Return the number of rows inserted return $this->db->affected_rows(); } return 0; }
Key Fixes Recap:
- Model's
getid(): Returns the actual integer ID instead of a result array - Controller: Initializes the insert array, validates
pidbefore adding rows, and only runs insert if there's valid data - Error Handling: Adds logging for invalid rows to help debug issues with your CSV data
This should resolve the problem where you were trying to insert an array/object into the pid column, and ensure only valid rows are added to your target table.
内容的提问来源于stack exchange,提问作者Christianus Andre

