show post of category in index controller codeigniter - php

i completely new in ci and i build a project that have index page and show posts in this page with pagination, i have menu sidebar that contain categories , i want when i click each them show posts of that category. how can change my code to that?
home_controller
class Home extends Ci_controller {
function __construct() {
parent:: __construct();
$this->load->model('home_model');
$this->load->model('category_model');
$this->load->library('pagination');
}
function index() {
$category = $this->category_model->allCategory();
$config['base_url'] = base_url() . 'index.php/home/index/page/';
$config['total_rows'] = $this->home_model->countall();
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$this->pagination->initialize($config);
$posts = $this->home_model->all($config['per_page'], $page);
$setting = $this->home_model->setting('about');
$pagination = $this->pagination->create_links();
$this->template->load('home', array('posts' => $posts, 'pagination' => $pagination, 'category' => $category, 'setting' => unserialize($setting['value'])));
}
}
home_model
class Home_model extends CI_Model {
function __construct() {
parent::__construct();
}
function allPost() {
$all = $this->db->get('posts')->result_array();
$data_send = array();
foreach ($all as $key => $value) {
$data = array();
$category = $this->db->get_where('catpost', array('post_id' => $value['post_id']))->result_array();
$data['id'] = $value['post_id'];
$data['title'] = $value['title'];
$data['create_time'] = $value['create_time'];
$data['content'] = $value['content'];
$data['username'] = $value['username'];
$data['category'] = $category;
$data_send[] = $data;
}
return $data_send;
}
function all($limit, $start) {
$lastpost = $this->db->select('post_id')->order_by('create_time DESC')->limit($limit, $start)->get('post')->result_array();
$idarr = array();
foreach ($lastpost as $key => $value) {
$idarr[] = "'{$value['post_id']}'";
}
$ids = implode(',', $idarr);
$sql = "select tbl_post.post_id, tbl_category.name, tbl_post.title, tbl_post.content, tbl_post.create_time, tbl_post.author_id, tbl_user.username from `tbl_category` join `tbl_post_category` on `tbl_post_category`.`category_id`=`tbl_category`.`category_id` join `tbl_post` on `tbl_post`.`post_id`=`tbl_post_category`.`post_id` join tbl_user on tbl_user.user_id=tbl_post.author_id where tbl_post.post_id in($ids) ORDER BY tbl_post.post_id DESC";
$allpost = $this->db->query($sql)->result_array();
$posts = array();
foreach ($allpost as $key => $value) {
$postid = $value['post_id'];
if (array_key_exists($postid, $posts)) {
$posts[$postid]['category'] .= ",{$value['name']}";
} else {
$posts[$postid] = array(
'post_id' => $postid,
'title' => $value['title'],
'content' => $value['content'],
'create_time' => $value['create_time'],
'username' => $value['username'],
'category' => $value['name']);
}
}
return $posts;
}
function setting($name = NULL) {
$ret = NULL;
if ($name != NULL) {
$this->db->where('name', $name);
$ret = $this->db->get('setting')->result_array()[0];
} else {
$ret = $this->db->get('setting')->result_array();
}
return $ret;
}
function countall() {
Return $this->db->count_all('posts');
}
}
view part of category
<?php
foreach($category as $key => $value){
$name='category['.$value['name'].']';
echo '<li><a href='.$value['name'].'>'.$value['name'].'</a></li>';
}
?>

Related

An uncaught Exception was encountered Type: Error Message: Class 'BaseController' not found

<?php
defined('BASEPATH') or exit('No direct script access allowed');
class index extends BaseController
{
public function __construct()
{
parent::__construct();
$this->load->model('P_pmb', 'p_pmb');
}
public function index()
{
$data['title'] = 'Dashboard';
$this->render('index/index', $data);
}
public function pendaftarprodi1()
{
$data['title'] = 'Grafik Berdasarkan Prodi 1';
$prodi = $this->p_pmb->listProdi();
foreach ($prodi as $key => $p) {
$prodi[$key]['jumlah'] = $this->p_pmb->jumlahPendaftarProdi1($p['id_prodi']);
$prodi[$key]['jumlah2'] = $this->p_pmb->jumlahPendaftarProdi2($p['id_prodi']);
$prodi[$key]['size'] = rand(10, 30);
}
//grafik 1
$result = null;
foreach ($prodi as $p => $prod) {
// if ($prod['jumlah'] > $sum) {
// $sum = $prod['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $prod['nama_prodi'],
"jumlah" => $prod['jumlah'],
"y" => $prod['size'],
// "sliced" => $sliced,
// 'selected' => $selected
];
}
$data['pendaftar'] = $prodi;
$data['grafik1'] = json_encode($result);
$this->render('index/grafik1', $data);
}
public function pendaftarprodi2()
{
$data['title'] = 'Grafik Berdasarkan Prodi 2';
$prodi = $this->p_pmb->listProdi();
foreach ($prodi as $key => $p) {
$prodi[$key]['jumlah'] = $this->p_pmb->jumlahPendaftarProdi1($p['id_prodi']);
$prodi[$key]['jumlah2'] = $this->p_pmb->jumlahPendaftarProdi2($p['id_prodi']);
$prodi[$key]['size'] = rand(10, 30);
}
//grafik 2
$hasil = null;
foreach ($prodi as $p => $prod) {
$hasil[$p] = [
"name" => $prod['nama_prodi'],
"jumlah" => $prod['jumlah2'],
"y" => $prod['size'],
// "sliced" => $sliced,
// 'selected' => $selected
];
}
$data['pendaftar'] = $prodi;
$data['grafik2'] = json_encode($hasil);
$this->render('index/grafik2', $data);
}
public function pendaftarprestasi()
{
$pendaftarprestasi = $this->p_pmb->listpendaftarprestasi();
foreach ($pendaftarprestasi as $key => $p) {
$pendaftarprestasi[$key]['jumlah'] = $this->p_pmb->jumlahpendaftarprestasi($p['tingkat_prestasi']);
$pendaftarprestasi[$key]['size'] = rand(10, 30);
}
$result = null;
$sum = 0;
foreach ($pendaftarprestasi as $p => $pendpres) {
//if ($pendpres['jumlah'] > $sum) {
// $sum = $pendpres['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $pendpres['tingkat_prestasi'],
'jumlah' => $pendpres['jumlah'],
'y' => $pendpres['size'],
// $sliced => $sliced,
// $selected => $selected
];
}
$data['pendaftarprestasi'] = $pendaftarprestasi;
$data['grafikprestasi'] = json_encode($result);
$this->render('index/grafikprestasi', $data);
}
public function jalurmasuk()
{
$pendaftar = $this->p_pmb->listjalurpendaftar();
foreach ($pendaftar as $key => $p) {
$pendaftar[$key]['jumlah'] = $this->p_pmb->jumlahjalurpendaftar($p['nama_jalur']);
$pendaftar[$key]['jumlah'] = rand(10, 30);
}
$result = null;
$sum = 0;
foreach ($pendaftar as $p => $jalmask) {
//if ($jalmask['jumlah'] > $sum) {
// $sum = $jalmask['jumlah'];
// $sliced = true;
// $selected = true;
// }
$result[$p] = [
"name" => $jalmask['nama_jalur'],
'jumlah' => $jalmask['jumlah'],
'y' => $jalmask['jumlah'],
// $sliced => $sliced,
// $selected => $selected
];
}
$data['jalur_masuk'] = $jalmask;
$data['grafikmasuk'] = json_encode($result);
$this->render('index/grafikmasuk', $data);
}
public function pendapatan()
{
$data['title'] = 'Grafik Pendapatan Berdasarkan Bank';
$bank = $this->p_pmb->listBank();
$pendaftar = $this->p_pmb->pendaftarBank();
$categories = null;
$lunas = null;
$belum_lunas = null;
$sumTotal = 0;
foreach ($bank as $i => $b) {
$categories[] = $b['bank'];
foreach ($pendaftar as $key => $value) {
if ($b['id_bank'] == $value['id_bank']) {
if ($value['is_bayar'] == '1') {
$sumTotal += intval($value['total']);
$lunas[] = intval($value['total']);
} else {
$belum_lunas[] = intval($value['total']);
}
}
}
}
$result[] = [
'name' => 'Pendapatan',
'data' => $lunas,
];
$data['subtitle'] = 'Total Pendapatan Rp.' . $sumTotal;
$grafik['id_bank'] = json_encode($result);
$grafik['categories'] = json_encode($categories);
$data['grafikpendapatan'] = $grafik;
$this->render('index/grafikpendapatan', $data);
}
public function bank()
{
$data['title'] = 'Grafik Pendapatan Berdasarkan Bank';
$bank = $this->p_pmb->listBank();
$pendaftar = $this->p_pmb->pendaftarBank();
$categories = null;
$lunas = null;
$belum_lunas = null;
$sumTotal = 0;
foreach ($bank as $i => $b) {
$categories[] = $b['bank'];
foreach ($pendaftar as $key => $value) {
if ($b['id_bank'] == $value['id_bank']) {
if ($value['is_bayar'] == '1') {
$sumTotal += intval($value['total']);
$lunas[] = intval($value['total']);
} else {
$sumTotal += $value['jumlah'];
$belum_lunas[] = intval($value['total']);
}
}
}
}
$result[] = [
'name' => 'Lunas',
'data' => $lunas,
];
$result[] = [
'name' => 'Belum Lunas',
'data' => $belum_lunas,
];
$data['subtitle'] = 'Total Pendaftar: ' . $sumTotal;
$data['id_bank'] = $bank;
$data['grafikbank'] = json_encode($result);
$this->render('index/grafikbank', $data);
}
}
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class BaseController extends CI_Controller
{
public function render($filename, $data)
{
$this->load->view('template/app_top', $data);
$this->load->view('template/template_scripts', $data);
$this->load->view($filename, $data);
$this->load->view('template/app_bottom', $data);
}
}

REST API generation for Opencart

I tried to generate a REST API for my customers, categories, products, coupons, manufacturers and all others to use it in my Android application, but I can't get any solution.
Can anyone tell me how to create APIs in opencart 3.0.2.0?
Make a custom controller in catalog > Controller > api folder
Create controller file name: allproducts.php
You can copy following code and paste of allproducts.php
<?php
class ControllerApiAllproducts extends Controller {
private $error = array();
// All Products
public function index(){
$products = array();
$this->load->language('catalog/product');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error[]['no_json']= "No JSON";
$product_total = $this->model_catalog_product->getTotalProducts();
$results = $this->model_catalog_product->getProducts();
foreach ($results as $result) {
if (is_file(DIR_IMAGE . $result['image'])) {
$image = $this->model_tool_image->resize($result['image'], 40, 40);
} else {
$image = $this->model_tool_image->resize('no_image.png', 40, 40);
}
$special = false;
$product_specials = $this->model_catalog_product->getProductSpecials($result['product_id']);
foreach ($product_specials as $product_special) {
//if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
$special = $product_special['price'];
//break;
// }
}
$shop_products['shop_products'][] = array(
'product_id' => $result['product_id'],
'image' => $image,
'name' => $result['name'],
'model' => $result['model'],
'price' => $result['price'],
'special' => $special,
'quantity' => $result['quantity'],
'status' => $result['status']
);
}
if (isset($this->request->get['json'])) {
echo json_encode($shop_products);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Product info Page
public function productInfo(){
$this->load->language('catalog/product');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$product_details = array();
$error['fail'] = 'Failed';
if (isset($this->request->get['product_id'])) {
//$product_details['product_id'] = $this->request->get['product_id'];
$product_details = $this->model_catalog_product->getProduct($this->request->get['product_id']);
echo json_encode($product_details);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Category Listing Page
public function categories(){
$shop_categories = array();
$this->load->model('catalog/category');
$error['fail'] = 'Failed';
if (isset($this->request->get['json'])) {
$shop_categories =$this->model_catalog_category->getCategories();
echo json_encode($shop_categories);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Product Listing By Category
public function categoryList(){
$this->load->model('catalog/category');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['path'])) {
$url = '';
$path = '';
$parts = explode('_', (string)$this->request->get['path']);
$category_id = (int)array_pop($parts);
foreach ($parts as $path_id) {
if (!$path) {
$path = (int)$path_id;
} else {
$path .= '_' . (int)$path_id;
}
$category_info = $this->model_catalog_category->getCategory($path_id);
}
} else {
$category_id = 0;
}
$category_info = $this->model_catalog_category->getCategory($category_id);
if ($category_info) {
$url = '';
//$data['categories'] = array();
$results = $this->model_catalog_category->getCategories($category_id);
foreach ($results as $result) {
$filter_data = array(
'filter_category_id' => $result['category_id'],
'filter_sub_category' => true
);
}
$products = array();
$filter_data = array(
'filter_category_id' => $category_id
);
$product_total = $this->model_catalog_product->getTotalProducts($filter_data);
$products = $this->model_catalog_product->getProducts($filter_data);
echo json_encode($products); die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// All Manufacturers Listing
public function manufactureList() {
$this->load->model('catalog/manufacturer');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
$manufactureList = array();
if (isset($this->request->get['json'])) {
$manufactureList = $this->model_catalog_manufacturer->getManufacturers();
echo json_encode($manufactureList);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Manufactur info Page
public function manufactureInfo() {
$this->load->model('catalog/manufacturer');
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['manufacturer_id'])) {
$manufactureInfo = $this->model_catalog_manufacturer->getManufacturer($manufacturer_id);
echo json_encode($product_details);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
// Category Listing Page
public function specialProduct(){
$specialProduct = array();
$this->load->model('catalog/product');
$this->load->model('tool/image');
$error['fail'] = 'Failed';
if (isset($this->request->get['json'])) {
$specialProduct = $this->model_catalog_product->getProductSpecials();
echo json_encode($specialProduct);die;
} else {
$this->response->setOutput(json_encode($error));
}
}
}
I made following APIs and its path (see Postman apps):
ALL Products : http://examples.com/index.php?route=api/allproducts&json
Product By ID : http://examples.com/index.php?route=api/allproducts/productInfo&json&product_id=30
ALL Categories : http://examples.com/index.php?route=api/allproducts/categories&json
Category Wise Product : http://examples.com/index.php?route=api/allproducts/categoryList&json&path=25_28
ALL Manufacturers : http://examples.com/index.php?route=api/allproducts/manufactureList&json
Manufactur By ID : http://examples.com/index.php?route=api/allproducts/manufactureInfo&manufacturer_id=11
Special Products : http://examples.com/index.php?route=api/allproducts/specialProduct&json

where clause not working in codigniter

I am showing products in a page with a where clause. I am selecting everything from the product table where the category is vegetable, but it's not working. I am new in CodeIgniter. I also checked many questions on the Internet, but nothing is working. If there is anything in this code that is wrong, please tell me.
The controller part:
<?php
class products_list extends CI_Controller
{
function __construct() {
parent::__construct();
$this->load->helper('url'); //to load css base url
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model("pagination_model");
$this->load->library("pagination");
$this->load->library('table');
}
function vegetables(){
$this ->load->view('includes/header1');
$config['base_url']='http://localhost/mah/index.php/products_list/vegetables';
$vegetable="Vegetable";
$config['total_rows']= $this->db->get_where('product', $vegetable)->num_rows();
$config['per_page'] = 12;
$config['num_links'] = 20;
$config['full_tag_open']='<div id="pagination">';
$config['full_tag_close']='</div>';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["results"] = $this->pagination_model->
fetch_product($config["per_page"], $page);
$data["links"] = $this->pagination->create_links();
$this->load->view("product_display", $data);
$this ->load->view('includes/footer');
}
public function article($id)
{
$this ->load->view('includes/header');
$this->load->model('articles_model', 'product');
$article = $this->product->find($id);
$this->load->view('product_details', compact('article'));
}
}
?>
The model part:
<?php
class pagination_model extends CI_Model
{
public function __construct() {
parent::__construct();
}
public function record_count() {
$where="category='vegetable'";
return $this->db->count_all("product");
}
public function fetch_product($limit, $start) {
$this->db->limit($limit, $start);
$query = $this->db->get("product");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
}
?>
Controller method :
cutomise your links as per your requirements and base_url as well
public function vegetables() {
$data = array('title' => 'Products');
$config = array();
$config['base_url'] = base_url().'products_list/vegetables';
$config['total_rows'] = $this->pagination_model->countRows('products');
$config['per_page'] = 5;
$config['attributes'] = array('class' =>'item');
$config['first_link'] = 'First';
$config['cur_tag_open'] = '<a class="active item">';
$config['cur_tag_close'] = '</a>';
$config['next_link'] = 'Next';
$config['last_link'] = 'Last';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$data["products"] = $this->pagination_model->getProducts('',$config["per_page"],$page);
$data["categoriesData"] = $this->pagination_model->getProducts('vegetable',$config["per_page"],$page);
$data["links"] = $this->pagination->create_links();
print_r($data);die;
//$this->load->view('templates/header',$data);
$this->load->view('product_display',$data);
//$this->load->view('templates/footer');
}
Your model :
getProducts fetch both type of data
1: if u provide category as first param then it return categories data
2: Otherwise fetch whole table;
public function getProducts($category = NULL, $limit = NULL, $start = NULL)
{
$limit = $limit == NULL ? '' : $limit;
$start = $start == NULL ? '' : $start;
$this->db->order_by('id', 'DESC');
$this->db->limit($limit, $start);
if (empty($category))
{
$query = $this->db->get('products');
}
else
{
$query = $this->db->get_where('products', array('category' => $category));
}
if ($query->num_rows() > 0)
{
foreach ($query->result_array() as $row)
{
$data[] = $row;
}
return $data;
}
}
// total count method
public function countRows($table) {
if (empty($table)) return false;
return $this->db->count_all($table);
}
last but not the least :
add this in controller __contruct() method
public function __construct()
{
parent::__construct();
$this->load->helper(array('url','text','html','form'));
$this->load->library(array('session','form_validation','pagination'));
$this->load->database();
$this->load->model('YourModel');
}
try with this...
$config['total_rows']= $this->db->get_where('product', array('title' => $vegetable))
->num_rows();

Can't insert in database with Codeigniter

I'm trying to add everything from a table (transactions) then try to insert all the totals to another table(reports_daily), but nothing is inserted.
transaction.php
public function index()
{
$this->load->model('transactions_model');
$transresult = $this->transactions_model->get_transactions_list();
$data['translist'] = $transresult;
$this->load->view('transactions_view',$data);
}
function create() {
$transresult = $this->transactions_model->get_transactions_list();
$data['translist'] = $transresult;
$sum=0;
$items=0;
$orders=0;
$date=$translist[0]->date_d;
for ($i=0; $i<count($translist); ++$i){
$sum += $translist[$i]->total_amount;
$items += $translist[$i]->no_items;
$orders++;
}
$data = array(
'date_d' => $date,
'total_items' => $items,
'total_orders' => $orders,
'total_sales' => $sum
);
//$this->db->set($data);
//$this->db->insert('reports_daily', $data);
$this->transactions_model->insert_reports($data);
$this->index();
}
transactions_model.php
function get_transactions_list()
{
$sql = 'select * from transactions order by date_d desc';
$query = $this->db->query($sql);
$result = $query->result();
return $result;
}
function insert_reports($data)
{
$this->db->insert('reports_daily', $data);
return;
}
Help :(
$translist is not exist on controller. So use $transresult[0] instead of $translist[0];
function create() {
$transresult = $this->transactions_model->get_transactions_list();
$sum=0;
$items=0;
$orders=0;
$date = $transresult[0]->date_d;
for ($i=0; $i<count($translist); ++$i){
$sum += $translist[$i]->total_amount;
$items += $translist[$i]->no_items;
$orders++;
}
$data = array(
'date_d' => $date,
'total_items' => $items,
'total_orders' => $orders,
'total_sales' => $sum
);
//$this->db->set($data);
//$this->db->insert('reports_daily', $data);
$this->transactions_model->insert_reports($data);
$this->index();
}

result ammount not showing correct

On my pagination results it is not showing correct for example it should show Showing 1 to 5 of 5 (1 Pages) on view but for some reason it is showing Showing -19 to 0 of 5 (1 Pages)
I am not sure why it is showing -19 should show 1 $the $data['results'] not working correct how can I fix it.
<?php
class Users_group extends MX_Controller {
public function index() {
$this->load->library('paginations');
$this->load->model('admin/user/model_user_group');
$data['title'] = "Users Group";
// Sort
if (null !==($this->uri->segment(3))) {
$sort = $this->uri->segment(3);
} else {
$sort = 'name';
}
// Order
if (null !==($this->uri->segment(4))) {
$order = $this->uri->segment(4);
} else {
$order = 'asc';
}
// Page
if (null !==($this->uri->segment(3))) {
$page = $this->uri->segment(3);
} else {
$page = 1;
}
$url = '';
// Sort
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
// Order
if (null !==($this->uri->segment(4))) {
$url .= $this->uri->segment(4);
}
// Page Number
if (null !==($this->uri->segment(3))) {
$url .= $this->uri->segment(3);
}
$admin_limit = "20";
$filter_data = array(
'sort' => $sort,
'order' => $order,
'start' => ($page - 1) * $admin_limit,
'limit' => $admin_limit
);
$user_group_total = $this->model_user_group->getTotalUserGroups();
$results = $this->model_user_group->getUserGroups($filter_data);
foreach ($results as $result) {
$data['user_groups'][] = array(
'user_group_id' => $result['user_group_id'],
'name' => $result['name'],
'edit' => site_url('admin/users_group/edit' .'/'. $result['user_group_id'] . $url)
);
}
$url = '';
if ($order == 'asc') {
$url .= 'desc';
} else {
$url .= 'asc';
}
$data['sort_name'] = site_url('admin/users_group' .'/'. 'name' .'/'. $url);
$url = '';
$paginations = new Paginations();
$paginations->total = $user_group_total;
$paginations->page = $page;
$paginations->limit = $admin_limit;
$paginations->url = site_url('admin/users_group' .'/'. $url . '{page}');
$data['pagination'] = $paginations->render();
$paginations_lang = "Showing %d to %d of %d (%d Pages)";
$data['results'] = sprintf($paginations_lang, ($user_group_total) ? (($page - 1) * $admin_limit) + 1 : 0, ((($page - 1) * $admin_limit) > ($user_group_total - $admin_limit)) ? $user_group_total : ((($page - 1) * $admin_limit) + $admin_limit), $user_group_total, ceil($user_group_total / $admin_limit));
$data['sort'] = $sort;
$data['order'] = $order;
$this->load->view('template/user/users_group_list.tpl', $data);
}
public function getForm() {
$data['title'] = "Users Group";
$this->load->view('template/user/users_group_form.tpl', $data);
}
}

Categories