Loop from category to sub category in PHP - 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);

Related

Unable to retrieve the sub categories

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

mysqli_fetch_array reading result as null?

Any idea why this is showing a result of null? I'm guessing it has to do with where I put $link before I did the query, but it has to be done that way, correct?
function getcatposts($cat_id) {
$qc = #mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = #mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
Updated code:
function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}
New issue is that its displaying like this:
http://gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png
When the DB looks like this:
http://gyazo.com/1ead8bd0f150838dae3ee4a476419679.png
It should be displaying all three of them and this is a function meaning it will keep redoing all the code until it can't query anymore data. Any ideas?
The problem here is that you're trying to echo the values outside your loop. The variables inside the loop will get overwritten on each iteration and at the end of looping, the variable will hold the value of the last iteration.
If you want to display all the values, move the echo statement inside your loop, like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title = $row['topic_subject'];
$topic_id = $row['topic_id'];
echo $topic_title.'<br/>';
echo $topic_id.'<br/>';
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name = $row2['cat_name'];
echo $cat_name.'<br/>';
}
If you care about the order, you could store the titles, ids and cat_names in arrays like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title[] =$row['topic_subject'];
$topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name[] =$row2['cat_name'];
}
And then loop through them:
for ($i=0; $i < count($topic_id); $i++) {
if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
{
echo $cat_name[$i].'<br/>';
echo $topic_title[$i].'<br/>';
echo $topic_id[$i].'<br/>';
}
}
Your function displays only one result because your echo is outside the while loop...
Put the Echo statements inside the loop, or you will print only the last result!
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
echo $topic_title;
echo '<br />';
echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
echo $cat_name;
echo '<br />';
}

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];
}

Nested Navigation

I want to make a Navigation with 2 levels.
My Code so far
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
foreach ($list as $kat) {
echo '<li>' . $kat['name'] . '</li>';
}
?>
Nested Sets are at the moment too tricky for me.
I want at the end this.
<li>$kat['name']
<li>$kat['name'] from PID</li>
</li>
MySQL:
http://i46.tinypic.com/35052m0.png - IMG
No I want to get the things our of the MySQL DB see the image Link.
MySQL:
id—–pid——name
1——0——–name1
2——0——–name2
3——0——–name3
4——3——–name3.1
5——3——–name3.2
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[$row['id']] = $row;
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='".$row['id']."' ORDER BY name");
$res = mysql_query($sql);
while($rw = mysql_fetch_assoc($res)){
$list[$row['id']]['sub'][] = $rw;
}
}
echo "<pre>";
print_r($list);
?>

Categories