How to fetch products from database using codeigniter framework?

by hal.littel , in category: PHP Frameworks , 6 months ago

How to fetch products from database using codeigniter framework?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 6 months ago

@hal.littel 

To fetch products from a database using the CodeIgniter framework, you can follow these steps:

  1. 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.
  2. 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 {
    // ...
}


  1. 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
}


  1. In your controller, load the Product_model using $this->load->model('Product_model'); at the beginning of your controller file.
  2. 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);
}


  1. 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
    // ...
}


  1. 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.