Category with Subcategory PHP/MySQL - php

i have MySql Table name 'category', in that table i have
id catname parent_id
1 animals
2 vegs
3 dog 1
4 cat 1
5 carrot 2
i just wanna display this data in html nested 'ul' like
<ul>
<li>Animals
<ul>
<li>dog</li>
<li>cat</li>
</ul>
</li>
<li>Vegs
<ul>
<li>Carrot</li>
</ul>
</li>
</ul>
with php, please help me to get this data with php(CodeIgniter) and display.

Here are the three components for your question: controller, model and view...
<!-- THE VIEW -->
<ul>
<?php foreach($main_cat->result() as $rowm) : ?>
<li><?php echo $rowm->catname ?>
<ul>
<?php
$id = $rowm->id;
$sec_cat = $this->yourmodel->get_secondary($id);
foreach($sec_cat->result() as $rows) :
?>
<li><?php echo $rows->catname ?></li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
<!-- THE CONTROLLER -->
<?php
class Welcome extends CI_Controller {
function index()
{
$data['main_cat'] = $this->yourmodel->get_main();
$this->load->view('welcome_view',$data);
}
}
?>
<!-- THE MODEL -->
<?php
class Yourmodel extends CI_Model {
function get_main()
{
$this->db->where('parent_id','');
$query = $this->db->get('category');
return $query;
}
function get_secondary($parent)
{
$this->db->where('parent_id',$parent);
$query = $this->db->get('category');
return $query;
}
}
?>

Related

Any best idea to do this? Codeigniter 4, how to make: no request on View, only on Controller?

Here is my Controller:
$data = [
'mainMenu' => $this->mainmenuModel->getAll(),
'subMenu' => $this->submenuModel->getAll()
];
return view('dashboard/user', $data);
Here is my View:
<div class="navigation">
<div class="container">
<div class="row">
<div class="navbar">
My Web Admin
<nav class="nav">
<ul>
<?php foreach($mainMenu as $dtmainmenu): ?>
<li>
<?=$dtmainmenu['menu_name']; ?>
<ul>
<?php $idmainmenu = $dtmainmenu['id_mainmenu'] ?>
<?php $db = \Config\Database::connect(); ?> // AVOID DOING THIS ON VIEW
<?php $submenu = $this->db->query("SELECT * FROM submenu WHERE id_mainmenu = $idmainmenu"); ?> // AVOID DOING THIS ON VIEW
<?php foreach($submenu as $dtsubmenu): ?>
<li><?=$dtsubmenu['submenu_name']; ?></li>
<?php endForeach; ?>
</ul>
</li>
<?php endForeach; ?>
</ul>
</nav>
</div>
</div>
</div>
</div>
Tables Example is below:
Main Menu
id_mainmenu
menu_name
content
1
Home
Kontent
2
About Us
Kontent
3
News
Kontent
4
Travel
Kontent
5
Contact
Kontent
Sub Menu
id_submenu
id_mainmenu
submenu_name
1
3
Local News
2
3
Sport News
3
4
Adventures
4
4
Must Visits
5
4
Local Attrac
What is the best way to do this?
Create a core library that handles data. Fetch all data to single arrray, than use it in your view properly.

Issue in pulling pages from the database

I am having problems pulling the pages through in PHP and HTML I have used :-
<li>
<!-- Pulling Categories from the database
dynamically -->
<?php
$nav_subjects = find_all_subjects(['visible' => $visible]);
while($nav_subject =
mysqli_fetch_assoc($nav_subjects)) {
?>
<span class="opener"><?php echo h($nav_subject['menu_name']); ?></span>
Which pulls the categories dynamically from the database and displays them with a drop down arrow just how I wanted but the pages will not show underneath them here's the code I have used for that bit:-
<!-- Categories listed correctly let's pull the pages for each one -->
<?php
if($nav_subject['id'] == $subject_id) {
$nav_pages = find_pages_by_subject_id($nav_subject['id'], ['visible' => $visible]);
while($nav_page = mysqli_fetch_assoc($nav_pages)) {
?>
<ul>
<li>
<?php echo h($nav_page['menu_name']); ?>
</li>
</ul>
<?php } // while $nav_pages
} // if($nav_subject['id'] == $subject_id)
} // while $nav_subjects ?>
</li>
<?php
mysqli_free_result($nav_subjects);
mysqli_free_result($nav_pages);
?>
I am pulling in the SQL from another page which is loaded correctly as the categories load and display correctly.
I will be grateful for any ideas.
I have also tried to echo back the sql result but nothing is shown.
I have now got it working with the following code:-
<li>
<?php $nav_subjects = find_all_subjects(['visible' => $visible]);
while($nav_subject = mysqli_fetch_assoc($nav_subjects)) {?>
<span class="opener"><?php echo h($nav_subject['menu_name']); ?></span>
<ul>
<?php if($nav_subject['id'] == $subject_id);
$nav_pages = find_pages_by_subject_id($nav_subject['id'], ['visible' => $visible]);
while($nav_page = mysqli_fetch_assoc($nav_pages)) { ?>
<li><?php echo h($nav_page['menu_name']); ?></li>
<?php } ?>
<?php } ?>
</ul>
But now it is listing the secondary subjects as a child of the first instead of individual subjects of their own.
*********Resolved**********
please advise if you think the code could be better i've currently used :-
<li>
<?php $nav_subjects = find_all_subjects(['visible' => $visible]);?>
<?php while($nav_subject = mysqli_fetch_assoc($nav_subjects)){?>
<span class="opener"><?php echo h($nav_subject['menu_name']);?></span>
<ul>
<?php if($nav_subject['id'] == $subject_id);
$nav_pages = find_pages_by_subject_id($nav_subject['id'], ['visible' => $visible]);
while($nav_page = mysqli_fetch_assoc($nav_pages)) { ?>
<a href="<?php echo url_for('index.php?id=' . h(u($nav_page['id']))); ?>">
<?php echo h($nav_page['menu_name']); ?></a>
<?php } ?>
<?php mysqli_free_result($nav_pages); ?>
</ul>
<?php } ?>
<?php mysqli_free_result($nav_subjects); ?>
</li>

Category product menu bar not linking

I made a category menu bar on my website so you can click on a category and see products of that category, but its not working for me and I must be doing something wrong.
Some database information:
categories table:
Row 1: id
Row 2: name
In the products table:
Row: category_id
I used a db helper (db_helper.php)
<?php if (!function_exists('get_categories_h')) {
function get_categories_h(){
$CI = get_instance();
$categories = $CI->Product_model->get_categories();
return $categories;
} } ?>
This is the my Product_model file where I made the get_categories function:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Product_model extends CI_model {
public function saveProduct($data) {
$this->db->insert('products', $data);
$product_id = $this->db->insert_id();
return $product_id;
}
public function get_product_details($product_id) {
$arrReturn = array();
$this->db->select('*');
$this->db->from('products');
$this->db->where('product_id', $product_id);
$query = $this->db->get();
$result = $query->result_array();
if (!empty($result)) {
$arrReturn = $result[0];
}
return $arrReturn;
}
/*
Get categories
*/
public function get_categories(){
$this->db->select('*');
$this->db->from('categories');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
}
?>
And this is the menu bar in my view file where I'm loading all my categories.
<div class="container-fluid">
<div class="row">
<div class="col-lg-1">
<div id="categorymenu">
<center> <h3>Categorieën</h3> </center>
<ul class="list-group">
<?php foreach (get_categories_h() as $category) : ?>
<li class="list-group-item">
<a href="<?php echo $category->id; ?>"><?php echo $category['name']; ?>
</a>
</li>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
</div>
I am able to echo all the categories from my database but the links are not working.
I hope someone can help me,
Thanks!
Looks like you are creating a nonsense URL for the href value. Unless the 'id' field of the 'categories' table contains values that use a "controller/method/id" scheme the links you are creating don't go anywhere.
The 'id' field probably just contains numbers. Yes?
If so, your links probably look something like http://example.com/123 which isn't going to go anywhere unless you have a controller named "123".
You need hrefs that go somewhere. I recommend using the anchor() function of Codeigniter URL Helper. You will need to load that helper before this example will work.
<?php foreach (get_categories_h() as $category) : ?>
<li class="list-group-item">
<?php echo anchor("controller_name/controller_method/{$category->id}", $category['name']); ?>
</li>
<?php endforeach; ?>
Without the anchor() function it would be written
<?php echo $category['name']; ?>
Try this:
<li class="list-group-item">
<a href="<?php echo $category->id;?>">
<?php echo $category['name']; ?>
</a>
</li>

How to assign html code to variable in codeigniter?

I want to assign some html code to variable and that variable is in controller.
headerview.php
<header id="header" class="header">
<div class="container">
<!-- LOGO -->
<div class="logo"><img src="<?php echo base_url()?>public/images/logo.png" alt=""></div>
<!-- END / LOGO -->
<!-- NAVIGATION -->
<nav class="navigation">
<div class="open-menu">
<span class="item item-1"></span>
<span class="item item-2"></span>
<span class="item item-3"></span>
</div>
<!-- MENU -->
<ul class="menu">
<?php if($isAdmin ){ ?>
<?php
if($title=='Dashboard'){
?>
<li class="current-menu-item">Admin Dashboard</li>
<?php
}else{
?>
<li>Admin Dashboard</li>
<?php
}
?>
<?php } else { ?>
<?php
if($title=='Dashboard'){
?>
<li class="current-menu-item">User Dashboard</li>
<?php
}else{
?>
<li>User Dashboard</li>
<?php
}
?>
<?php } ?>
<?php
if($title=='Courses' || $title=='Add/Edit Categories' || $title=='Upload Manager'){
?>
<li class="current-menu-item">
Courses
<ul class="sub-menu">
<li>Categories</li>
<li>Courses</li>
<li>Upload Manager</li>
</ul>
</li>
<?php
}else{
?>
<li>
Courses
<ul class="sub-menu">
<li>Categories</li>
<li>Courses</li>
<li>Upload Manager</li>
</ul>
</li>
<?php
}
?>
<?php
if($title=='Users' || $title=='User Roles' || $title=='Subscription'){
?>
<li class="current-menu-item">
Users
<ul class="sub-menu">
<li>Roles</li>
<li>Subscription</li>
</ul>
</li>
<?php
}else{
?>
<li>
Users
<ul class="sub-menu">
<li>Roles</li>
<li>Subscription</li>
</ul>
</li>
<?php
}
?>
<?php
if($title=='Sales' || $title=='Payout Details'){
?>
<li class="current-menu-item">
Sales
<ul class="sub-menu">
<li>Transactions</li>
<li>Payouts</li>
</ul>
</li>
<?php
}else{
?>
<li>
Sales
<ul class="sub-menu">
<li>Transactions</li>
<li>Payouts</li>
</ul>
</li>
<?php
}
?>
</ul>
<!-- END / MENU -->
<!-- LIST ACCOUNT INFO -->
<ul class="list-account-info">
<!-- MESSAGE INFO -->
<!-- END / MESSAGE INFO -->
<!-- NOTIFICATION -->
<!-- END / NOTIFICATION -->
<li class="list-item account">
<?php
$userId=$this->session->userdata('cp_adminid');
$profilePic="";
$userQ=$this->Adminmodel->getuser();
foreach ($userQ->result() as $rowuser){
$profilePic=$rowuser->profilePic;
}
?>
<div class="account-info item-click">
<?php if($profilePic!=''){ ?>
<img alt="" src="<?php echo base_url();?>private/<?php echo $userId;?>/<?php echo $profilePic;?>">
<?php }else{?>
<img src="<?php echo base_url()?>public/images/default-profile_pic.png" alt="">
<?php }?>
</div>
<div class="toggle-account toggle-list">
<ul class="list-account">
<li><i class="icon md-config"></i>Setting</li>
<li><i class="icon md-arrow-right"></i>Sign Out</li>
</ul>
</div>
</li>
</ul>
<!-- END / LIST ACCOUNT INFO -->
</nav>
<!-- END / NAVIGATION -->
</div>
</header>
This header is come to all pages in application. So I want it to assign some variable called headerContent and it is located in Admin_controller. That render function called from any another controller that extends Admin_controller and then it loads the headeview to that pages.
Admin_controller
class Admin_controller extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->model("Adminmodel","",true);
$headerview = 'headerview';
$this->render($headerview); # calling render() function in same class
}
protected $headerview = 'headerview';
protected function render($headerContent) {
$view_data = array( 'headerContent' => $headerContent);
$this->load->view($this->headerview);
}
}
Another controller below that extends Admin_controller called this render function.
Adminhome_controller.php
<?php
require APPPATH . '/controllers/admin/Admin_controller.php';
class Adminhome extends Admin_Controller{
public function __construct(){
parent::__construct();
$this->load->model("Adminmodel","",true);
public function index(){
$data['content']=$this->load->view("admin/adminhomeview",'',true);
$data['title']='Dashboard';
$adminId=$this->session->userdata('cp_adminid');
$permissions=$this->Adminmodel->getpermissions($adminId);
$row = $permissions->row();
$data['isAdmin'] = 0;
if($row->view == 1 or $row->add == 1 or $row->edit == 1 or $row->deleteRole == 1 ){
$data['isAdmin'] = 1;
}
$this->render($headerContent);
// $this->load->view("admin/headerview",$data);
}
}
?>
But it showing error like Message: Undefined variable: headerContent in Adminhome_controller.php.
you culd create a template view file containing
template view:
<html>
<?php $data = array('permission' => $permission); ?>
<?php $this->load->view('templateincludes/header',$data); ?>
<?php $this->load->view($main_content); ?>
<?php $this->load->view('templateincludes/footer'); ?>
</html>
controler:
$data = array('permission' => '1', 'main_content' => 'folder_to_your_view/view_file_you_want_to_load');
$this->load->view('template', $data);
header view:
<?= $permission ?>
But it showing error like Message: Undefined variable: headerContent
in Adminhome_controller.php
There is no variable with the name $headerContent inside extended class. Seems like you want access the parent/base class's variable.
To overcome this, you can declare protected field inside Parent Controller (Admin_controller.php), and access it inside child controller :
class Admin_controller extends CI_Controller{
protected $headerContent; // declare protected field
protected $headerview = 'headerview';
function __construct()
{
parent::__construct();
$this->load->model("Adminmodel","",true);
$headerview = 'headerview';
$this->render($headerview); # calling render() function in same class
}
protected function render($headerContent) {
$view_data = array( 'headerContent' => $headerContent);
$this->headerContent = $headerContent; // assign value into $headerContent field
$this->load->view($this->headerview);
}
}
And you can access it directly inside child class (Adminhome_controller.php) by using :
$this->render($this->headerContent);

fetching data from database - php codeigniter

I want to fetch some data (student details) from database but my code is not working.
This is my Controller
public function Student_Detail()
{
$student_id = $this->uri->segment(3);
$record = $this->WebAdmin_Model->Student_Details($student_id);
$this->load->view('admin/template/header.php');
$this->load->view('admin/students/student_details', $record);
$this->load->view('admin/template/footer.php');
}
This is my Model
public function Student_Details($student_id)
{
$query = $this->db->query("SELECT s.`student_id`,
s.`std_email`,
s.`std_fname`,
s.`std_lname`
FROM `student_main` AS s
WHERE s.`student_id` = $student_id");
return $query->result();
}
This is my View
<section class="panel">
<div class="user-heading">
<img src="<?=base_url();?>images/profile-avatar.jpg" alt="">
</div>
<ul class="nav nav-pills nav-stacked">
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
</ul>
</section>
Note that there is not problem with the query. I want to know how to fetch student details. It gives me the following error. Message : Undefined variable: record
Try this:
In your controller:
$data['record'] = $this->WebAdmin_Model->Student_Details($student_id);
$this->load->view('admin/students/student_details', $data);
And in your view:
<ul class="nav nav-pills nav-stacked">
<?php
foreach($record->$row){
?>
<li> <?php echo $row->std_fname; ?></li>
<li> <?php echo $row->std_lname; ?></li>
<li> <?php echo $row->std_email; ?></li>
<?php
}
?>
</ul>
You need to pass your model data into record array then pass into view
Controller
$student_id = $this->uri->segment(3);
$record['data'] = $this->WebAdmin_Model->Student_Details($student_id);// store data into record array
$this->load->view('admin/template/header.php');
$this->load->view('admin/students/student_details', $record);
$this->load->view('admin/template/footer.php');
Use foreach loop to retrieve data
Views
<?php
foreach($data as $record)// use foreach loop
{ ?>
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
<?php } ?>
You need to do it like this, because codeigniter try to extract variable from $record and it fails. So to make possible, make it,
$record['record'] = $this->WebAdmin_Model->Student_Details($student_id);
and then in your view,
<ul class="nav nav-pills nav-stacked">
<li> <?php echo $record->std_fname; ?></li>
<li> <?php echo $record->std_lname; ?></li>
<li> <?php echo $record->std_email; ?></li>
</ul>
Because codeigniter will extract variable from $record array

Categories