SELECT Queries and creating an infinate loop in PHP - php

I am trying to create multiple loops in PHP to select parent and child items. i have this code:
<?php
$counter = 0;
$sql="SELECT * from shop_categories where parent = '' order by name ASC ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
$flag = 1;
$current_parent_sequence = $result["sequence"];
echo '<strong>'.$result["name"].'</strong><br>';
while($flag == 1) {
$counter++;
$sql2="SELECT * from shop_categories where parent = '".$current_parent_sequence."' order by name ASC ";
$rs2=mysql_query($sql2,$conn);
if(mysql_num_rows($rs2) > 0) {
while($result2=mysql_fetch_array($rs2)) {
$current_parent_sequence = $result2["sequence"];
echo $counter.' - '.$result2["name"].'<br>';
}
} else {
$flag = 0;
}
}
}
?>
then i have this data in my table - http://postimg.org/image/o2p31xd1j/
so it should show the parent items and its child items and their child items and so on but its only showing:
Cat 1
1 - Sub Cat 1
1 - Sub Cat 2
Cat 2
Cat 3
4 - Sub Cat 1

Please try below code. It might help you. You need create function which will call recursively.
function getChild($conn, $id) {
$rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '$id' order by name ASC ");
while($result = mysqli_fetch_assoc($rs)) {
$current_parent_sequence = $result["sequence"];
$parent = $result["parent"];
echo "--" . $result["name"] . "<br>";
if($parent != 0)
getChild($conn, $current_parent_sequence);
}
}
$rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '' order by name ASC ");
while($result = mysqli_fetch_assoc($rs)) {
$current_parent_sequence = $result["sequence"];
$parent = $result["parent"];
echo $result["name"] . "<br>";
getChild($conn, $current_parent_sequence);
}
Use mysqli as mysql is deprecated.

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);

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

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);

PHP paging, viewing a certain page first

This is my script for the paging on my site when the user clicks on a league.
The league is then echoed to the screen, and if the league is over 3 rows then it splits it up in to several pages.
What I am doing after is depending on where the user is in the league (the SQL query is using ORDER BY the total points column in the table), e.g if the user is on page one of the league table then for it to display that page first, but if the user is on page 3 of the league table then for that page to displayed first.
Does anyone know a way in order for me to achieve this?
//Recently updated from answer
$sql="SELECT members.username, members.total_points FROM members, members_leagues WHERE members.username = members_leagues.username AND
members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC";
$result=mysql_query($sql);
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row($result)){
if ($row[username] == $_SESSION[username]) {
$team_position = $i;
$found = true;
}
$i++;
}
$rowsPerPage = 3;
$pageNum = ceil($i/$rowsPerPage);
//end of recently updated
if(isset($_GET['page']))
$pageNum = $_GET['page'];
$offset = ($pageNum - 1) * $rowsPerPage;
$counter = $offset + 1;
$query = " SELECT members.username, members.teamname, members.total_points, FROM members, members_leagues WHERE members.username = members_leagues.username AND members_leagues.sub_league = '$chosenleague' ORDER BY members.total_points DESC " . " LIMIT $offset, $rowsPerPage";
$result = mysql_query($query) or die('Error, query failed');
echo "<h3 style=\"color:red;\">$chosenleague</h3>";
echo "<table>";
echo "<tr><th>Position</th>";
echo "<th>Team</th>";
echo "<th>Points/Overall</th>";
echo "<th>Points/Last Race</th>";
echo "<th>Team Setup</th></tr>";
while($row = mysql_fetch_array($result))
{
if($row[username] == $_SESSION[username])
echo "<tr style=\"color:red;\"><td>";
else
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $row[teamname];
echo "</td><td>";
echo $row[total_points];
echo "</td><td>";
echo "</td><td>";
echo "</td></tr>";
$counter++;
}
echo "</table>";
$query = "SELECT COUNT(members.username) AS numrows FROM members, members_leagues WHERE members.username = members_leagues.username
AND members_leagues.sub_league = '$chosenleague'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
$maxPage = ceil($numrows/$rowsPerPage);
$self = $_SERVER['PHP_SELF'];
$nav = '';
if ($pageNum > 1)
{
$page = $pageNum - 1;
$prev = " << Prev ";
$first = " First ";
}
else
{
$prev = '';
$first = '';
}
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = " Next >> ";
$last = " Last ";
}
else
{
$next = '';
$last = '';
}
echo "<div id=\"pagenum\">Page $pageNum of $maxPage ". $first . $last . $prev . $next ."</div>";
You can do it via mysql or php:
With PHP:
Found the position of the requested record in the array, then calculate the page you have to extract and execute the corresponding query. Something like.
$i = 0;
$found = false;
$team_position = 0;
while (!$found && $row = mysql_fetch_row) {
if ($row['team'] == 'team_your_searching_for') {
$team_position = $i;
$found = true;
}
$i++;
}
//calculate $top and $bottom
...
$sql = "SELECT * FROM members LIMIT $top, $bottom;";
...
With MySQL:
You can create a query that generates an autoincrement value and another that selects from the other's result. I mean
-- get the the selected member's position
SELECT team, pos FROM (SELECT team, points, #position = #position + 1 AS pos FROM members ORDER BY points) WHERE team = #the_team_your_searching_for;
-- get the nr of members
SELECT COUNT(*) FROM members;
...
-- calculate the page you wanna extract (#top, #bottom), and extract it
SELECT * FROM members LIMIT #top, #bottom;

Categories