新手求助:将指定PHP代码转换为CodeIgniter代码
Convert Raw PHP Database Code to CodeIgniter Style
Hey there! Since you're new to CodeIgniter, let's walk through converting your raw PHP database query into CodeIgniter's cleaner, safer approach using its built-in Database Class. First, let's break down what your original code does: it fetches id_matpel values from the matpel table, sorts them by bobot descending then nama_matpel ascending, stores them in an array, and loops through that array.
Step 1: Use CodeIgniter's Model (Best Practice)
CodeIgniter encourages separating database logic into models for better maintainability. Here's how to create a model for your query:
<?php class Matpel_model extends CI_Model { public function get_matpel_ids() { // Note: Your original SQL has a redundant `WHERE id_matpel` clause (no condition) // I've kept it out here since it doesn't filter any rows—double-check if you meant to add a condition! // Build the query using CodeIgniter's query builder $this->db->select('id_matpel'); $this->db->from('matpel'); $this->db->order_by('bobot', 'DESC'); $this->db->order_by('nama_matpel', 'ASC'); $query = $this->db->get(); // Check if we have results if ($query->num_rows() > 0) { // Option 1: Return a 2D array (each item is ['id_matpel' => 'value']) return $query->result_array(); // Option 2: Return a 1D array of just the ids (simpler for your loop) // return array_column($query->result_array(), 'id_matpel'); } // Return empty array if no results return []; } }
Step 2: Call the Model from Your Controller
Next, load the model in your controller and use it to get the data, then loop through it:
<?php class Your_Controller extends CI_Controller { public function your_method() { // Load the model first $this->load->model('Matpel_model'); // Get the array of matpel ids $arraymatpel1 = $this->Matpel_model->get_matpel_ids(); // Loop through the array (adjust based on which option you used in the model) // If using Option 1 (2D array): foreach ($arraymatpel1 as $keymatpel => $value) { $matpelid = $value['id_matpel']; // Add your logic here for each $matpelid } // If using Option 2 (1D array), the loop is simpler: // foreach ($arraymatpel1 as $matpelid) { // // Add your logic here for each $matpelid // } } }
Key Notes for New CodeIgniter Users:
- No Manual Database Connections: CodeIgniter handles database connections automatically once you configure your database settings in
application/config/database.php. - Query Builder Safety: The query builder helps prevent SQL injection (especially if you add dynamic conditions later—use
$this->db->where()with parameter binding). - Redundant WHERE Clause: Your original SQL had
WHERE id_matpelwith no condition—this doesn't filter any rows, so I omitted it. If you intended to add a condition (likeWHERE id_matpel = ?), feel free to adjust the code accordingly!
内容的提问来源于stack exchange,提问作者241196
相关产品推荐
相关产品推荐

