Unable to retrieve the sub categories - php

Hello I have tried to make categories and sub categories and trying to call sub categories as --sub cat name because I placed the category and sub category in the same table is used nested option. But, that is not working for me.
Can anyone help me out this this categories are getting but unable to get sub categories
<select name="category" class="dropdown">
<?php
$query1 = $this->db->query('SELECT * FROM categories');
foreach($query1->result() as $cat_name) {
if($cat_name->cat_name == $cat_name->parent)
echo "<option>". $cat_parent = $cat_name->cat_name."</option>";
$query2 = $this->db->query("SELECT * FROM categories WHERE parent = '$cat_parent '");
foreach($query2->result() as $sub_cat) {
if($sub_cat->cat_name != $sub_cat->parent) {
echo "<option> --" . $sub_cat->cat_name . "</option>";
}
}
}
?>
</select>

Try following function which should work for you and it is in core php so,you have to implement yourself in to codeigniter
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER BY id ASC";
$result=$con->query($sql);
if (mysqli_num_rows($result) > 0)
{
$user_tree_array[] = "<ul>";
while ($row =$result->fetch_object())
{
$user_tree_array[] = "<li>". $row->name."</li>";
$user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
}
$user_tree_array[] = "</ul><br/>";
}
return $user_tree_array;
}
And call it as
$res = fetchCategoryTreeList();
foreach ($res as $r)
{
echo $r;
}
hope it will help you

Related

Building menu dynamically in PHP based on data in database is too slow

I am trying to create dynamic menu using the below code, but it takes too much time to load:
<?php
ob_start();
include ('admin/db/db.php');
echo '<li>Exports';
$sql3 = "SELECT * FROM category_master where type = 'Export' order by sequence asc ";
$result3 = mysqli_query($connection, $sql3);
if (mysqli_num_rows($result3) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows3 = mysqli_fetch_assoc($result3))
{
$cid = $userrows3['product_category_id'];
$cname = $userrows3['category_name'];
echo '<li>' . $cname . '';
$sql4 = "SELECT group_product FROM products,category_master,cat_wise_pro where category_master.product_category_id = cat_wise_pro.category_id and products.product_id = cat_wise_pro.product_id and category_master.product_category_id =$cid group by products.group_product ";
$result4 = mysqli_query($connection, $sql4);
if (mysqli_num_rows($result4) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows4 = mysqli_fetch_assoc($result4))
{
$gname = $userrows4['group_product'];
echo '<li>' . $gname . '';
$sql5 = "SELECT product FROM products,group_products where products.group_product = group_products.group_product and products.group_product = '$gname'";
$result5 = mysqli_query($connection, $sql5);
if (mysqli_num_rows($result5) > 0)
{
// output data of each row
echo '<ul>';
while ($userrows5 = mysqli_fetch_assoc($result5))
{
$pname = $userrows5['product'];
echo '<li>' . $pname . '';
}
echo '</ul>';
}
}
echo '</ul>';
}
}
}
echo '</ul>';
?>
should i use view instead of table...find below the view i create
Any ideas how to make it faster?
What your code does is:
categories = load C categories from DB
foreach category:
groups = load G groups from DB
foreach group:
products = load products from DB
which sends 1 + C x G queries to database. What you should do is:
products = load products with groups with categories
$tree = [];
foreach ($products as $p):
$tree[$p['category']][$p['group']][] = $p;
foreach ($tree as $category => $groups):
foreach ($groups as $group => $products):
foreach ($products as $p):
...
Use JOIN to fetch the data at once, e.g. something like:
SELECT p.name as product, g.name as group, c.name as category
FROM product p
JOIN group_product g ON p.group_product = g.id
JOIN category_master c ON g.category = c.id;

Find number of levels in a tree using MySQL

My rows have related row and those rows can have related rows. This tree can go down many levels (unknown). How can I find the number of levels my tree is according to one parameter?
For example:
select * from category a
inner join category b on a.row=b.relatedRow
inner join category c on b.row=c.relatedRow where a.row=?
So if there are items in a, level 1. If there are items in b, level 2 and so on. This way I can find that if row=1, there are 3 levels of other items that are related.
create two php functions one is for getting main category and another one is for getting subcategories of main category.
function GetCategory($Cat_Id, $Cat_Name="")
{
$level = "";
echo $sql = "SELECT * FROM category WHERE 1=1 AND Cat_ParentId='0'";
$result = #mysql_query($sql);
while($row = #mysql_fetch_assoc($result))
{
if(!empty($Cat_Id))
{
if($row['Cat_Id']==$Cat_Id)
{
$selected = "selected='selected'";
}
else
{
$selected = "";
}
}
else
{
$selected="";
}
$resul .= $level.$row['Cat_Name']."<br />";
$resul .= GetSubCateogry($row['Cat_Id'], $level);
}
return $resul;
}
function GetSubCateogry($Cat_Id, $level)
{
$level .= "--";
$sql = "SELECT * FROM category WHERE Cat_ParentId = '$Cat_Id'";
$result = #mysql_query($sql);
while($row = #mysql_fetch_assoc($result))
{
if(!empty($Cat_Id))
{
if($row['Cat_Id']==$Cat_Id)
{
$selected = "selected='selected'";
}
else
{
$selected = "";
}
}
else
{
$selected="";
}
$resul .= $level.$row['Cat_Name']."<br />";
$resul .= GetSubCateogry($row['Cat_Id'], $level);
}
return $resul;
}
echo GetCategory(1);

Loop from category to sub category in PHP

We are having a structure like the way you are seeing in below screenshot:
And our database structure looks like this:
Here in database table "PID" is the Parent ID in which 0 = Parent ID. And rest PID is the parent id of same id.
Now we are trying to get all the sub category of "Brand" Or "Footware" so it should show all (sub-sub-category and sub-sub-sub-category) the sub category details under that tree. Can this be done through PHP? any loop or any way?
Thank you!
try this
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER BY id ASC";
$result=$con->query($sql);
if (mysqli_num_rows($result) > 0)
{
$user_tree_array[] = "<ul>";
while ($row =$result->fetch_object())
{
$user_tree_array[] = "<li>". $row->name."</li>";
$user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
}
$user_tree_array[] = "</ul><br/>";
}
return $user_tree_array;
}
call function here
$res = fetchCategoryTreeList();
foreach ($res as $r)
{
echo $r;
}
Try like this:
<?php
//connect to mysql and select db
$conn = mysqli_connect('localhost', 'rootuser', 'rootpwd','dbname');
if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));
//call the recursive function to print category listing
category_tree(0);
//Recursive php function
function category_tree($catid){
global $conn;
$sql = "select * from category where pid ='".$catid."'";
$result = $conn->query($sql);
while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' . $row->category;
category_tree($row->id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
endwhile;
}
//close the connection
mysqli_close($conn);
?>
Hope this will help.
I used this function in my project, it is a recursive function.
/**** GET ALL CATEGORIES FUNCTION *******/
function categoryChild($id, $spacing = '') {
$s = "SELECT * FROM category WHERE parent_cat_id = $id ";
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_array($r)) {
$children[$row['category_id']]['category_name'] = $spacing.$row['category_name'];
$children[$row['category_id']]['id'] = $row['category_id'];
$children[$row['category_id']]['child'] = categoryChild($row['category_id'], $spacing . ' ');
}
}
return $children;
}
> /************ GET ALL CATEGORIES FUNCTION****************/
$allcategory = categoryChild(0);
print_r($allcategory);

Diplay items for category PHP and echo categories as link to each view

Hello im learning so im sorry if this is a fool question. (also sorry about my bad english)
Im trying to display the items from a particular category.
In my Database, i have set my categories like this.
And the Products or Items like this,
Im using this code to display tree categories.
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$list = '<li>'.$parent['name'].'</li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
But i cant find a good way to convert the categories in links, so each time a users clic one category i will display the items for that category..
What would be the best for that.
If you can point me in the right direction, some tutorial, or something, would be really , really great.
It sounds like you are looking for some sort of java tree viewer, like this example?
http://dftree.sourceforge.net/dftree/example.html
There are several open source options for this (I have no experience of the one I list above, I just use it as an example). I'm sure I have used a tree viewer in the past that took a list format like you are using - I suggest you have a search around sourceforge.
Your question is not foolish, but is quite long... and many of us are quite lazy :-)
Ok i solve this
This is the code for the page with the menu and categories
<?php
function hasChild($parent_id)
{
$sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = '" . $parent_id . "'";
$qry = mysql_query($sql);
$rs = mysql_fetch_array($qry);
return $rs['count'];
}
function CategoryTree($list,$parent,$append)
{
$productpage = "index.php";
$list = '<li><a href='.$productpage.'?'.'cat='.$parent['id'].'>'.$parent['name'].'</a></li>';
if (hasChild($parent['id'])) // check if the id has a child
{
$append++;
$list .= "<ul class='child child".$append."'>";
$sql = "SELECT * FROM category WHERE parent_id = '" . $parent['id'] . "'";
$qry = mysql_query($sql);
$child = mysql_fetch_array($qry);
do{
$list .= CategoryTree($list,$child,$append);
}while($child = mysql_fetch_array($qry));
$list .= "</ul>";
}
return $list;
}
function CategoryList()
{
$list = "";
$sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
$qry = mysql_query($sql);
$parent = mysql_fetch_array($qry);
$mainlist = "<ul class='parent'>";
do{
$mainlist .= CategoryTree($list,$parent,$append = 0);
}while($parent = mysql_fetch_array($qry));
$list .= "</ul>";
return $mainlist;
}
?>
And the code for the product page
<?php
$producto = mysql_escape_string($_GET['producto']);
$tablename = "productos";
$res = mysql_query("SELECT * FROM `$tablename` WHERE `id` = '$producto'");
$row = mysql_fetch_assoc($res);
$uid = $row["id"];
$titulo = $row["titulo"];
$descripcion = $row["descripcion"];
$modelo = $row["modelo"];
$img = $row["img"];
// echo the output to browser or compound an output variables here
echo "ID = $uid
<br />Titulo = $titulo
<br>Descripcion = $descripcion
<br>Modelo = $modelo
<br>Imagen = <img src=\"../admin/$img\" width=\"40px\" height=\"40px\" >
<hr />";
?>

Display List of Moodle 2.4 Courses for a user Outside of Moodle

I am trying to create a page where it displays a bullet list of Course Title and link to any courses that user is teacher of for Moodle 2.4.
I found this code here and it works for displaying Moodle course categories but not the courses for a user. I am not a programmer so any help would be very appreciated.
<?php
$con = mysql_connect("localhost","moodle","moodle");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
if (isset($result)!=1) {
$message = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";
///Display Course Categories
$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);
$tmp_categories = array();
foreach ($categories AS $row) {
$row['id'] = (int) $row['id'];
$row['parent'] = (int) $row['parent'];
if (!$tmp_categories[$row['parent']])
$tmp_categories[$row['parent']] = array();
$tmp_categories[$row['parent']][] = $row;
}
$course_catetories = buildNode($tmp_categories);
echo '<ul>';
foreach ($course_catetories as $course_catetory) {
print_category_child($course_catetory);
}
echo '</ul>';
function print_category_child($category) {
echo '<li>' . $category['name'];
if (array_key_exists('children', $category)) {
echo '<ul>';
foreach ($category['children'] as $child) {
print_category_child($child);
}
echo '</ul>';
}
echo '</li>';
}
function buildNode($inputArray, $parent = 0) {
$return = array();
foreach ($inputArray[$parent] AS $key => $row) {
if (#$inputArray[$row['id']]) {
$row['children'] = buildNode($inputArray, $row['id']);
}
$return[] = $row;
}
return $return;
}
function mysql_fetch_all($result) {
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {
}
return array_filter($all);
}
///END Course Display
?>'`
Look at your Mysql query :
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
Your results are a list of categories' names from the table "mdl_course_categories".
If you want to display a list of courses names, do it using the right table "mdl_course". It may be something like :
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT id, fullname FROM mdl_course WHERE category = "your_course_category_here");
while($row = mysql_fetch_array($result)){
echo $row[0];
echo "<br>";
echo $row[1];
}

Categories