@hal.littel
To fetch products from a database using the CodeIgniter framework, you can follow these steps:
- First, make sure you have configured your database connection in the database.php file located in the config folder. Set the hostname, username, password, and database name according to your server configuration.
- Create a model for your products. In the models folder, create a new file called Product_model.php (replace Product with your desired name). Inside this file, define a class Product_model that extends CI_Model:
1
2
3
|
class Product_model extends CI_Model {
// ...
}
|
- Inside the Product_model class, create a method called get_products that will fetch the products from the database. The method can look like this:
1
2
3
4
|
public function get_products() {
$query = $this->db->get('products'); // 'products' is the name of your database table
return $query->result(); // return the query result as an array of objects
}
|
- In your controller, load the Product_model using $this->load->model('Product_model'); at the beginning of your controller file.
- Create a method inside your controller that will fetch the products from the model and pass them to the view:
1
2
3
4
|
public function fetch_products() {
$data['products'] = $this->Product_model->get_products();
$this->load->view('products_view', $data);
}
|
- In the views folder, create a new file called products_view.php (replace products with your desired name) and display the products received from the controller:
1
2
3
4
5
|
foreach ($products as $product) {
echo $product->name; // Assuming 'name' is a column in your 'products' table
echo $product->price; // Assuming 'price' is a column in your 'products' table
// ...
}
|
- Finally, you can access the fetch_products method in your browser by navigating to the appropriate URL or by calling it from another method in your controller.
Note: This is a basic example of fetching products from a database using CodeIgniter. You can modify it according to your database structure and requirements.