Hi there,
i am new to code igniter, and trying to understand CI 3 first.
Now i am stuck with following situation:
I would like to get all books from a database, that is working fine.
but when I want to group it by category i am stuck.
below the first code block is the preferred situation, below that code block I tried to do this in CI 3 format.
Can someone help me out with:
- How do I create a model function with a query bases on other query results?
- how do I put this correct through the controller an make the output in the view?
PHP Code:
<?php
$categories = array();
$query = mysqli_query($conn, "SELECT id, name FROM categories");
$categories = mysqli_fetch_assoc($query);
foreach($categories as $category) {
?><h3><? echo $category['name']; ?></h3><?php
$books = array();
$category_id = $category['id'];
$query = mysqli_query($conn, "SELECT id, title, description, price FROM books WHERE category='$category_id'");
$books = mysqli_fetch_assoc($query);
foreach($books as $book) {
?><p><b><?php echo $book['title']; ?></b><br><br><?php echo $book['description'] ?><br><br><b><u><?php echo $book['price']; ?></u></b></p><?php
}
}
below I tried to start coding myself.
PHP Code:
// MODEL
class Books_model extends CI_Model {
public function __construct() {
$this->load->database();
}
public function get_books() {
$query = $this->db->get('books');
return $query->row_array();
}
}
// CONTROLLER
class Books extends CI_Controller() {
public function __construct()) {
$this->load->model('books_model');
}
public function index() {
$data['title'] = "Books";
$data['books'] = $this->books_model->get_books();
$this->load->view('template/header', $data);
$this->load->view('books/index', $data);
$this->load->view('template/footer');
}
}
// VIEW
?>
<h2><?php echo $title; ?></h2>
<?php foreach $books as $book): ?>
<p>
<h3><?php echo $book['title']; ?></h3>
<?php echo $book['description']; ?><br><br>
<b><u></b><?php echo $book['price']; ?></u></b>
</p>
<?php endforeach; ?>
Hopefully someone can help me out.
kindest regards.Dirk