i record number of queries of my website and in page the below script runs , 40 extra queries added to page .
how can I change this sql connection into a propper and light one
function tree_set($index)
{
//global $menu; Remove this.
$q=mysql_query("select id,name,parent from cats where parent='$index'");
if(mysql_num_rows($q) === 0)
{
return;
}
// User $tree instead of the $menu global as this way there shouldn't be any data duplication
$tree = $index > 0 ? '<ul>' : ''; // If we are on index 0 then we don't need the enclosing ul
while($arr=mysql_fetch_assoc($q))
{
$subFileCount=mysql_query("select id,name,parent from cats where parent='{$arr['id']}'");
if(mysql_num_rows($subFileCount) > 0)
{
$class = 'folder';
}
else
{
$class = 'file';
}
$tree .= '<li>';
$tree .= '<span class="'.$class.'">'.$arr['name'].'</span>';
$tree .=tree_set("".$arr['id']."");
$tree .= '</li>'."\n";
}
$tree .= $index > 0 ? '</ul>' : ''; // If we are on index 0 then we don't need the enclosing ul
return $tree;
}
//variable $menu must be defined before the function call
$menu = '....<ul id="browser" class="filetree">'."\n";
$menu .= tree_set(0);
$menu .= '</ul>';
echo $menu;
i heard , this can be done by changing it into an array , but i don't know how to do so
thanks in advance
Try this (untested code):
function tree_set($index)
{
//global $menu; Remove this.
$q=mysql_query("select id,name,parent from cats where parent='$index'");
if(mysql_num_rows($q) === 0)
return;
$cats = array();
$cat_ids = array();
while($arr=mysql_fetch_assoc($q))
{
$id = intval($arr['id']);
$cats[$id] = $arr;
}
$subFilesCountQuery="select parent,count(*) as subFileCount from cats where parent=".
join(" OR parent=",array_keys($cats))." GROUP BY parent";
$subFileCountResult=mysql_query($subFilesCountQuery);
while($arr=mysql_fetch_assoc($subFileCountResult))
{
$id = intval($arr['parent']);
$cats[$id]['subFileCount'] = $arr['subFileCount'];
}
// If we are on index 0 then we don't need the enclosing ul
$tree = $index > 0 ? '<ul>' : '';
foreach($cats as $id => $cat)
{
if($cat['subFileCount'] > 0)
$class = 'folder';
else
$class = 'file';
$tree .= '<li>';
$tree .= '<span class="'.$class.'">'.$arr['name'].'</span>';
$tree .=tree_set("".$arr['id']."");
$tree .= '</li>'."\n";
}
$tree .= $index > 0 ? '</ul>' : '';
What I'm doing is two queries: One to fetch all the categories (your original first query) followed by a second query to fetch all the subcategory counts in one fell swoop. I am also storing all categories in an array which you can loop through, rather than displaying as you fetch from the database.
It can be done by copying your data out into an array, and then using that copy: i.e.
while($arr=mysql_fetch_assoc($q))
{
$results[] = $arr;
}
later on, you then do whatever op you want on $results
The main problem with your code is you are mixing your display logic all in with your SQL query.
Select whole tree in single query, like "select id,name,parent from cats". Iterate on result, build array in PHP that will represent your tree, then draw HTML using array as source
Related
How to loop all records and display all the respective children using HTML <ul></ul>? I tried using PHP Do While but stuck at only 1 level.
MySQL (select * from user)
Desired output
Tree View
List View
The easy was is to do that with the help of array. Hope it helps.
$data = array();
foreach ($result as $item) {
$key = $item['name']; // or $item['info_id']
if (!isset($data[$key])) {
$data[$key] = array();
}
$data[$key][] = $item;
}
You can use this code:
$aResults; // it is your mysql result (array)
$resultSorted = array();
$resultSorted = recursiveList($aResults, '');
function recursiveList(&$aResults, $iKey)
{
$aChilds = '<ul>';
foreach ($aResults as $iLoopKey => $aResult) {
if ($aResult['parent'] == $iKey) {
unset($aResults[$iLoopKey]);
$aChilds .= '<li>' . $aResult['name'] . '</li>';
$aChilds .= recursiveList($aResults, $aResult['name']);
}
}
return $aChilds . '</ul>';
}
// Output example
echo '<pre>';
print_r($resultSorted);
As a result, I recived:
Also you'd better use 'parent_id' instead 'parent' in yours tables.
I have a table menu like this
i have problem to display like this with ul and li tag like 2nd picture.
please help me for the solution
menu_code|desc_code
1 | menu 1
1.1 | menu 1.1
1.2 | menu 1.2
1.2.1| menu 1.2.1
2 | menu 2
i want to display my table menu with concept "unlimited level menu".
I would consider changing your table structure. You will need to loop through each parent and children, you wouldnt want to do that with string splitting. I advice you to create an extra column parent_id and binding your items like that. After that its easy to crawl recursively through its children to create a ul > li structure.
Example recursive function:
public static function buildTree($items, $parent_id = null) {
$result = [];
foreach($items as $item) {
if($item->parent_id == $parent_id) {
$children = self::buildTree($items, $item->id);
if($children) {
$item->children = $children;
}
$result[$item->id] = $item;
}
}
return $result;
}
After that you can use the result of the build function to recursively create your menu structure:
public static function treeToHtml($tree, $level = 0) {
$result = '';
$result .= '<ul>';
foreach($tree as $item) {
$has_children = isset($item->children) && count($item->children) > 0;
if($has_children) {
$result .= '<li><a href="#">';
$result .= self::treeToHtml($item->children, $level + 1);
$result .= '</li>';
} else {
$result .= '<li><a href="#"></li>';
}
}
$result .= '</ul>';
return $result;
}
Edit function accordingly and statically all depends on the context you're using it in.
I'm trying to create a series of <ul> and <li> to create a directory/file structure to navigate some files created from a table in a dB. The table (tb_lib_manual) contains both files and folders.
If a record has a null entry for fileID then it is a folder not a file. each record has a parentID to show which folder is parent, for files and folders in the root this is 0.
The php code is thus:
class library_folders extends system_pageElement
{
private $html = '';
private $i = 0;
private $stmtArray = array();
private $objectArray = array();
function __construct()
{
parent::__construct();
$this->nextList();
}
function nextList($parentID = 0)
{
$qSQL = 'SELECT * FROM tb_lib_manual WHERE parentID=:parentID';
$stmtArray[$this->i] = $this->dbConnection->prepare($qSQL);
$stmtArray[$this->i]->bindValue(':parentID', $parentID, PDO::PARAM_INT);
$stmtArray[$this->i]->execute();
if($stmtArray[$this->i]->rowCount() > 0)
{
$display ='';
if($parentID != 0)
{
$display = ' style="display:none"';
}
$this->html .= '<ul' . $display . '>';
}
while ($this->objectArray[$this->i] = $stmtArray[$this->i]->fetchObject())
{
$this->html .= '<li>' . $this->objectArray[$this->i]->title;
if($this->objectArray[$this->i]->fileID == null)
{
//we have a folder!
$manualID = $this->objectArray[$this->i]->manualID;
$this->i ++;
$this->nextList($manualID);
$this->i--;
}
$this->html .= '</li>';
}
if($stmtArray[$this->i]->rowCount() > 0)
{
$this->html .= '</ul>';
}
echo $this->html;
}
function __destruct()
{
parent::__destruct();
}
}
The problem is when the code returns back to the while loop after calling itself it restarts the loop rather than carrying on where it left off, causing a repeat in the child folder. Is there either a better way to do this or am I doing something wrong!?
Table looks like this:
output like this:
'A ManualA ManualFolder 1Nasa exerciseA ManualA ManualFolder 1Nasa exercise'
Fixed the code, very silly mistake, echo in the wrong place...
class library_folders extends system_pageElement
{
private $html = '';
private $i = 0;
private $stmtArray = array();
private $objectArray = array();
function __construct()
{
parent::__construct();
$this->nextList();
echo $this->html;
}
function nextList($parentID = 0)
{
$qSQL = 'SELECT * FROM tb_lib_manual WHERE parentID=:parentID';
//echo $this->i;
$stmtArray[$this->i] = $this->dbConnection->prepare($qSQL);
$stmtArray[$this->i]->bindValue(':parentID', $parentID, PDO::PARAM_INT);
$stmtArray[$this->i]->execute();
if($stmtArray[$this->i]->rowCount() > 0)
{
$this->html .= '<ul>';
}
while ($this->objectArray[$this->i] = $stmtArray[$this->i]->fetchObject())
{
$this->html .= '<li>' . $this->objectArray[$this->i]->title;
if($this->objectArray[$this->i]->fileID == null)
{
//we have a folder!
$manualID = $this->objectArray[$this->i]->manualID;
$this->i ++;
$this->nextList($manualID);
$this->i--;
}
$this->html .= '</li>';
}
if($stmtArray[$this->i]->rowCount() > 0)
{
$this->html .= '</ul>';
}
}
function __destruct()
{
parent::__destruct();
}
}
Yes, there are better ways of doing this.
If you fetch the whole tree every time, you might as well load all the nodes into a big array (of objects), put each node's id as index and then loop over the array once to create the parent references by for example
// create a fake root node to start your traversal later on
// only do this if you don't have a real root node
// which I assume you don't
$root = (object) ["children" => []];
// loop over all nodes
foreach ($nodes as $node)
{
// if the node has a parent node that is not root
if ($node->parentId > 0)
{
// put it into it's parent's list of children
$nodes[ $node->parentId ]->children[] = $node;
}
else
{
// otherwise put it into root's list of children
$root->children[] = $node;
}
}
Complexity: You do one query and you have to iterate all your nodes once.
For this to work your nodes need to be objects. Otherwise each assignment to $node->children will create a copy of the assigned node where you wanted a reference.
If you do not want to fetch all nodes, you can go through your tree level by level by creating a list of node ids from the previous level.
function fetchLevel ($nodes, $previousLevelIds)
{
// get all children from the previous level's nodes
// I assume $previousLevelIds to be an array of integers. beware of sql injection
// I refrained from using prepared statements for simplicity
$stmt = $pdo->query("SELECT id, parentId FROM nodes WHERE parentId IN (".implode(",",$previousLevelIds).")");
// fetch nodes as instances of stdclass
$currentLevelNodes = $stmt->fetchAll(PDO::FETCH_OBJ);
$nextLevelIds = [];
foreach ($currentLevelNodes as $node)
{
// ids for next level
$nextLevelIds[] = $node->id;
// parent <-> child reference
$nodes[ $node->parentId ]->children[] = $node;
}
// fetch the next level only if we found any nodes in this level
// this will stop the recursion
if ($nextLevelIds)
fetchLevel($nodes, $nextLevelIds);
}
// start by using a fake root again
$root = (object) ["id" => 0, "children" => []];
$nodes = [0 => $root];
fetchLevel($nodes, [0]);
// or start with a specific node in the tree
$node = $pdo->query("SELECT id, parentId FROM nodes WHERE id = 1337")->fetch(PDO::FETCH_OBJ);
$nodes = [$node->id => $node];
fetchLevel($nodes, [$node->id]);
// or a number of nodes which don't even have to
// be on the same level, but you might fetch nodes multiple times
// if you it this way
Complexity: Number of queries <= height of your tree. You only iterate each fetched node once.
For displaying the tree as html list you iterate once more:
class Foo {
public $html;
public function getList ($nodes)
{
// outer most ul
$this->html = '<ul>';
$this->recurseList($nodes);
$this->html .= '</ul>';
}
protected function recurseList ($nodes)
{
foreach ($nodes as $node)
{
$this->html .= "<li><span>".$node->name."</span>";
if ($node->children)
{
if ($node->parentId > 0)
$this->html .= '<ul style="display:none">';
else
$this->html .= '<ul>';
$this->recurseList($node->children);
$this->html .= "</ul>";
}
$this->html .= "</li>";
}
}
}
Some unrelated remarks:
instead of a hard-coded style="display:none" you could just use a css rule like ul li ul {display:none} to hide all lists below root
I split fetching the data from the database and converting the data for displaying into two separate scripts, which is the standard when you develop using MVC. If you don't want to do this run the scripts in succession.
PHP itself is a template engine, but consider using another template engine to display your html like Smarty. I personally prefer smarty for it's simpler syntax.
stackoverflow answer on how to bind a PHP array to a MySQL IN-operator using prepared statements
if you need to fetch subtrees often consider using a special table structure to reduce the number of queries
i'm trying to create a hierarchical select menu with multiple selection.
i select the categories and i store them in an array comma separated.etc(1,5,10). everything works fine except that each time i select another value the while loop echo's duplicate values on drop down list.
Is there any other way i could do this without having duplicate values?
$tree = '<select name="an_det_category[]" class="an_det_category" multiple>';
$var=explode(",",$row_detail_rec['an_det_category']);
print_r(array_values($var))
foreach ($var as $var1){
$result10 = mysql_query("select * from announcment_categories where an_parendid=0 and an_langid=".$_GET['langid']."");
while ($row= mysql_fetch_array($result10)){
if ($row['an_location']==$var1){$ka='"selected="selected"">';
}else{
$ka='">';
}
$tree .= '<option value="'.$row['an_location'].$ka;
$tree .= $row['an_name'];
$tree .= '</option>';
$tree .= getLowerRanks($row['an_location'],1,$var1);
}
}
$tree .= '</select>';
Don't do a for loop. Just loop through the database results, and use in_array to test whether the current category is in one of the selected categories.
while ($row = mysql_fetch_array($result10)) {
if (in_array($row['an_location'], $var)) {
$ka = 'selected="selected"';
} else {
$ka = '';
}
$tree .= "<option value='{$row['an_location']}' $ka>";
$tree .= $row['an_name'];
$tree .= '</option>';
// I'm not sure what this is, or how to reproduce it in this version
// $tree .= getLowerRanks($row['an_location'], 1, $var1);
}
Following function arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
function buildHtmlList($array)
{
$maxlevel = 0;
foreach ($array as $key => $value)
{
$previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
$nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;
if ($value['parent'] != $previousparent)
{
echo "\n<ul>";
++$maxlevel;
}
echo "\n<li>" . $value['name'];
if ($nextparent == $value['parent'])
echo "</li>";
}
for ($i = 0; $i < $maxlevel; ++$i)
{
echo "\n</li>\n</ul>";
}
}
It arranges the array totally wrong. Have you noticed any wrong piece of code in following function?
The wrong piece is the whole logic of the function. You treat the array as a flat list (as it is!), however, you'd like to display a tree.
As a flat list can't be displayed as a tree, you need to change the flat list to a tree first and then write a function that displays a tree.
An example how to convert a flat array to a tree/multidimensional one is available in a previous answer.
Try something like this (where $array is formatted like your example):
$corrected_array = array();
// This loop groups all of your entries by their parent
foreach( $array as $row)
{
$corrected_array[ $row['parent'] ][] = $row['name'];
}
// This loop outputs the children of each parent
foreach( $corrected_array as $parent => $children)
{
echo '<ul>';
foreach( $children as $child)
{
echo '<li>' . $child . '</li>';
}
echo '</ul>';
}
Demo