Codeigniter_Blog_App/application/models/Post_model.php

71 lines
2.6 KiB
PHP
Raw Normal View History

2024-07-11 04:23:32 +00:00
<?php
class Post_model extends CI_Model {
public function __construct(){
$this->load->database();
}
//this is the function to get the posts
public function get_posts($slug = FALSE, $limit = FALSE, $offset = FALSE){
if($limit){
$this->db->limit($limit,$offset);
}
if($slug === FALSE){
$this->db->order_by('posts.id','DESC');
$this->db->join('categories','categories.id = posts.category_id');
$query = $this->db->get('posts');
return $query->result_array();
}
$query = $this->db->get_where('posts', array('slug' => $slug));
return $query->row_array();
}
//function to create posts
public function create_post($post_image){
$slug = url_title($this->input->post('title'));
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body'),
'category_id' => $this->input->post('category_id'),
'user_id' => $this->session->userdata('user_id'),
'post_image' => $post_image
);
return $this->db->insert('posts', $data);
}
//function to delete posts
public function delete_post($id){
$this->db->where('id', $id);
$this->db->delete('posts');
return true;
}
//function to update posts
public function update_post(){
//the post method of codeigniter retrieves the data from the POST when we submit the input
$slug = url_title($this->input->post('title'));
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'body' => $this->input->post('body')
);
$this->db->where('id',$this->input->post('id'));
return $this->db->update('posts', $data);
//update is an inbuilt codeigniter method
}
public function get_categories(){
$this->db->order_by('name');
$query = $this->db->get('categories');
return $query->result_array();
}
public function get_posts_by_category($category_id){
$this->db->order_by('category_id','DESC');
$this->db->join('categories','categories.id = posts.category_id');
$query = $this->db->get_where('posts', array('category_id' => $category_id));
return $query->result_array();
}
}