I have mysql query that gets all the parent ids to child map into an array, then i have a function to print out all child ids for a parent id.
what i want to accomplish now is get the username for each echoed child id using this function.
and paginate the result on each page if possible.
the mysql query + function to get the ids to childs map into array:
$res = $db->query('SELECT p.id AS parent, GROUP_CONCAT( c.id ) AS children
FROM rev_r_clients AS p
JOIN rev_r_clients AS c ON c.parent_client_id = p.id
GROUP BY p.id');
$parents = Array();
while($row = $res->fetch_assoc()) {
$parents[$row['parent']] = explode(',',$row['children']);
}
Now the Function that print out the children for a specific parent ID:
function subtree($id, $parents) {
echo $id;
echo ' <br> ';
if (isset($parents[$id]))
foreach ($parents[$id] as $child)
{
subtree($child, $parents);
}
Now any idea how to get the username from another MYSQL table ( rev_users )
and if possible paginate the result on each page?
Can't make a query for each row as the result is huge , thousand of child ids for each parent id.
Rewrite your query to return all the fields you need. Execute a new query for each row of the cursor is not a solution, but a workaround.
Related
Say I have 2 tables. parent & child where a parent can have many children.
I want to get the data in the following structure so:
[
{ parent_id:1, children: [{child_id: 1, parent_id:1},{ child_id:2, parent_id:1}],
{ parent_id:2, children: [{child_id: 3, parent_id:2},{ child_id:4, parent_id:2}],
{ parent_id:3, children: [{child_id: 5, parent_id:3},{ child_id:6, parent_id:3}]
]
JOIN gives me duplicate parent data for each child, and GROUP BY parent_id only gives me 1 child per parent.
Currently my solution is: SELECT * from parent loop through the results and then SELECT * FROM child WHERE parent_id = :parent_id. I feel there has to be a better way.
Is MySQL capable of performing this in fewer queries, if so how would I go about it?
EDIT: Hacky solution based on using GROUP_CONCAT:
$q = "SELECT p.*, GROUP_CONCAT(c.id,'|#|', c.column_2, '|#|', c.column3, '|#|', c.column4 SEPARATOR '###') AS children
FROM parent p
INNER JOIN child c ON p.id = c.parent_id";
$parents= query($q);
foreach ($parents as &$parent) {
$children = explode('###', $parent->children);
foreach ($children as &$child){
$child = array_combine(['id','col1','col2','col3'], explode('|#|', $child));
}
$parent->children = $children;
}
Essentially get the string with separators, explode into records, then explode into columns and remap the column values with hardcoded column names.
Leaving this open to tidier solutions.
If there are no better solutions, which would be more efficient.
1 query:group_concat where php manipulates the data into the desired structure.
n* queries: get all parents, then loop through them and get each parents children.
2 queries: get all parents, get all children, loop through and map them (currently using this)
I think you can use GROUP_CONCAT:
SELECT p.parent_id, GROUP_CONCAT(c.child_id) AS childs
FROM parent p
JOIN child c
ON p.parent_id = c.parent_id
GROUP BY p.parent_id
I have three tables like below:
[Category]->[SubCategory]->[Leaf]
-> means one-to-many relation;
Is it possible to make nested list with just one query?
Actual Query:
Select * from Category
join SubCategory
join Leaf
Intended Output:
Category
--Subcategory
----Leaf
----Leaf
--Subcategory
----Leaf
----Leaf
I know about composite design pattern; but lets say I have the result set from query and I want to manipulate the list above with minimal attempt.
Update
My question is without for loop and sub query, can it be done with the one query above, or what is the best way to generate 3 nested list like above from three tables?
Update:
What is the most optimized way to create a nested list like above from three tables in any database and in any language?
Use this query:
SELECT *
FROM Category c
JOIN SubCategory s ON s.CategoryID = c.ID
JOIN Leaf l ON l.SubCategoryID = s.ID
ORDER BY c.ID, s.ID, l.ID
Then in your PHP loop, print the Category name whenever it changes, print the SubCategory name whenever it changes, and print every Leaf name.
$last_cat = null;
while ($row = fetch()) {
if ($row['CategoryName'] !== $last_cat) {
echo $row['CategoryName'] . "\n";
$last_cat = $row['CategoryName'];
$last_subcat = null;
}
if ($row['SubCategoryName'] != $last_subcat) {
echo "--{$row['SubCategoryName']}\n";
$last_subcat = $row['SubCategoryName'];
}
echo "----{$row['LeafName']\n";
}
Please see the data tables and query below ..
Items
Id, Name
1, Item 1
2, Item 2
Categories
Id, Name, Parent ID
1, Furniture , 0
2, Tables, 1
3, Beds, 1
4, Dining Table, 2
5, Bar Table, 2
4, Electronics, 0
5, Home, 4
6, Outdoors, 4
7, Table lamp, 4
ItemCategory
ItemId, CategoryId
1, 2 .. Row1
2, 4 .. Row 2
2, 5 .. Row 3
ItemCategory table stores which items belongs to which category. An item can belong to top level and or sub category. there are about 3 level deep categories, that is, Tob level, sub level, and sub sub level.
Users select all of the categories they want to view and submit and I can query the database by using a sample query below..
SELECT * FROM items i INNER JOIN ItemCategory ic ON
ic.itemId = i.itemId AND ic.itemId IN ('comma separated category ids')
This works fine.
My question is that Is it possible to view all the items under a top level category even though it has not been directly assigned to the item. For example, if users select Furniture above, then it lists all the items belonging to its sub categories (even though the ItemCategory doesn't contain any record for it)??
I'm open to making necessary amendements to the data table or queries, please suggest a solution. Thank you.
Watcher has given a good answer, but I'd alter my approach somewhat to the following, so you have a structured recursive 2-dimensional array with categories as keys and items as values. This makes it very easy to print back to the user when responding to their search requirements.
Here is my approach, which I have tested:
$items = getItemsByCategory($topCategory);
//To print contents
print_r($items);
function getItemsByCategory($sid = 0) {
$list = array();
$sql = "SELECT Id, Name FROM Categories WHERE ParentId = $sid";
$rs = mysql_query($sql);
while ($obj = mysql_fetch_object($rs)) {
//echo $obj->id .", ".$parent." >> ".$obj->name."<br/>";
$list[$obj->name] = getItems($obj->id);
if (hasChildren($obj->id)) {
array_push($list[$obj->name],getItemsByCategory($obj->id));
}
}
return $list;
}
function getItems($cid) {
$list = array();
$sql = "SELECT i.Id, i.Name FROM Items p INNER JOIN ItemCategory ic ON i.id = ic.ItemId WHERE ic.CategoryId = $cid";
$rs = mysql_query($sql);
while ($obj = mysql_fetch_object($rs)) {
$list[] = array($obj->id, $obj->name);
}
return $list;
}
function hasChildren($pid) {
$sql = "SELECT * FROM Categories WHERE ParentId = $pid";
$rs = mysql_query($sql);
if (mysql_num_rows($rs) > 0) {
return true;
} else {
return false;
}
}
Hope this helps.
With recursion, anything is possible:
function fetchItemsByCat($cat, &$results) {
$itemsInCat = query("SELECT Items.Id FROM Items INNER JOIN ItemCategory ON ItemCategory.ItemId = Items.Id WHERE CategoryId = ?", array($cat));
while($row = *_fetch_array($itemsInCat))
array_push($results, $row['Id']);
$subCategories = query("SELECT Id FROM Categories WHERE Parent = ?", array( $cat ));
while($row = *_fetch_array($subCategories))
$results = fetchItemsByCat($row['Id'], $results);
return $results;
}
$startCat = 1; // Furniture
$itemsInCat = fetchItemsByCat($startCat, array());
The function is somewhat pseudo-code. Replace *_fetch_array with whatever Database extension you are using. The query function is however you are querying your database.
Also, this is untested, so you should test for unexpected results due to using an array reference, although I think it's good to go.
After calling the function, $itemsInCat will be an array of integer ids of all of the items/subitems that exist in the given start category. If you wanted to get fancy, you can instead return an array of arrays with each 2nd level array element having an item id as well as that item's assigned category id, item name, etc.
If you use MySQL, you're out of luck short of indexing your tree using typical techniques, which usually means pre-calculating and storing the paths, or using nested sets:
http://en.wikipedia.org/wiki/Nested_set_model
If you can switch to PostgreSQL, you can alternatively use a recursive query:
http://www.postgresql.org/docs/9.0/static/queries-with.html
Evidently, you can also recursively query from your app, but it's a lot less efficient.
Can someone help me with listing items by category in PHP?
I'm trying to create a simple list of books by category:
JavaScript
JavaScript Patterns
Object-Oriented JavaScript
Ajax
Ajax Definitive Guide
Bulletproof Ajax
jQuery
jQuery Cookbook
Learning jQuery 1.3
I have no problems with the data structure or SQL query:
BOOK: book_id, book_title, fk_category_id
CATEGORY: category_id, category_name
SELECT category.category_name, book.book_title
FROM category LEFT OUTER JOIN book
ON category.category_id = book.fk_category_id;
My problem is that I don't know how to write the PHP script to list the books under each category header.
I know enough to get the result set into an array, but then I'm stumped on using that array to group the items as shown.
Another Stack question addresses almost the same thing, but the responses stop short of solving the PHP code: List items by category
Thanks!
Add an ORDER BY category.category_name clause to your query so that as you loop through the resulting rows, the items in each category will be grouped together. Then, each time the category is different from the previous one seen, print out the category as the heading before printing the title.
$category = null;
foreach ($rows as $row) {
if ($row['category_name'] != $category) {
$category = $row['category_name'];
print "<h1>".$category."</h1>\n";
}
print $row['book_title']."<br/>\n";
}
Order the results by category and then just iterate thru, putting a category header whenever the category name changes.
The ordering is most easily done in the SQL query. You don't even need an intermediate array.
SELECT category.category_name, book.book_title
FROM category LEFT OUTER JOIN book
ON category.category_id = book.fk_category_id
ORDER BY category.category_name
And then for the PHP
$res = mysql_query($query);
$lastCategory = '';
while ($row = mysql_fetch_assoc($res))
{
if($row['category_name'] != $lastCategory)
{
$lastCategory = $row['category_name'];
echo "<br /><strong>$lastCategory</strong>";
}
echo $row['book_title'] . ' <br />';
}
You do not need to put all your results into an array first. You can just fetch them as you go.
I'm building a simple web app at the moment that I'll one day open source. As it stands at the moment, the nav is generated on every page load (which will change to be cached one day) but for the moment, it's being made with the code below. Using PHP 5.2.6 and MySQLi 5.0.7.7, how more efficient can the code below be? I think joins might help, but I'm after advice. Any tips would be greatly appreciated.
<?php
$navQuery = $mysqli->query("SELECT id,slug,name FROM categories WHERE live=1 ORDER BY name ASC") or die(mysqli_error($mysqli));
while($nav = $navQuery->fetch_object()) {
echo '<li>';
echo ''. $nav->name .'';
echo '<ul>';
$subNavQuery = $mysqli->query("SELECT id,name FROM snippets WHERE category='$nav->id' ORDER BY name ASC") or die(mysqli_error($mysqli));
while($subNav = $subNavQuery->fetch_object()) {
echo '<li>';
echo ''. $subNav->name .'';
echo '</li>';
}
echo '</ul>';
echo '</li>';
}
?>
You can run this query:
SELECT c.id AS cid, c.slug AS cslug, c.name AS cname,
s.id AS sid, s.name AS sname
FROM categories AS c
LEFT JOIN snippets AS s ON s.category = c.id
WHERE c.live=1
ORDER BY c.name, s.name
Then iterate thru the results to create the proper heading like:
// last category ID
$lastcid = 0;
while ($r = $navQuery->fetch_object ()) {
if ($r->cid != $lastcid) {
// new category
// let's close the last open category (if any)
if ($lastcid)
printf ('</li></ul>');
// save current category
$lastcid = $r->cid;
// display category
printf ('<li>%s', $r->cslug, $r->cname);
// display first snippet
printf ('<li>%s</li>', $r->cslug, $r->sname, $r->sname);
} else {
// category already processed, just display snippet
// display snippet
printf ('<li>%s</a>', $r->cslug, $r->sname, $r->sname);
}
}
// let's close the last open category (if any)
if ($lastcid)
printf ('</li></ul>');
Note that I used printf but you should use your own function instead which wraps around printf, but runs htmlspecialchars thru the parameters (except the first of course).
Disclaimer: I do not necessarily encourage such use of <ul>s.
This code is just here to show the basic idea of processing hierarchical data got with one query.
First off, you shouldn't query your database in your view. That would be mixing your business logic and your presentation logic. Just assign the query results to a variable in your controller and iterate through it.
As for the query, yup a join can do that in 1 query.
SELECT * -- Make sure you only select the fields you want. Might need to use aliases to avoid conflict
FROM snippets S LEFT JOIN categiries C ON S.category = C.id
WHERE live = 1
ORDER BY S.category, C.name
This will get you an initial result set. But this won't give you the data nicely ordered like you expect. You'll need to use a bit of PHP to group it into some arrays that you can use in your loops.
Something along the lines of
$categories = array();
foreach ($results as $result) {
$snippet = array();
//assign all the snippet related data into this var
if (isset($categories[$result['snippets.category']])) {
$categories[$result['snippets.category']]['snippet'][] = $snippet;
} else {
$category = array();
//assign all the category related data into this var;
$categories[$result['snippets.category']]['snippet'] = array($snippet);
$categories[$result['snippets.category']]['category'] = $category;
}
}
This should give you an array of categories which have all the related snippets in an array. You can simply loop through this array to reproduce your list.
I'd try this one:
SELECT
c.slug,c.name,s.name
FROM
categories c
LEFT JOIN snippets s
ON s.category = c.id
WHERE live=1 ORDER BY c.name, s.name
I didnt test it, though. Also check the indexes using the EXPLAIN statement so MySQL doesnt do a full scan of the table.
With these results, you can loop the results in PHP and check when the category name changes, and build your output as you wish.
Besides a single combined query you can use two separate ones.
You have a basic tree-structure here with branch elements (categories table) and leaf elements (snippets table). The shortcoming of the single-query solution is that you get owner brach-element repeatedly for every single leaf element. This is redundant information and depending on the number of leafs and the amount of information you query from each branch element can produce large amount of additional traffic.
The two-query solution looks like:
$navQuery = $mysqli->query ("SELECT id, slug, name FROM categories WHERE live=1 ORDER BY name")
or die (mysqli_error ($mysqli));
$subNavQuery = $mysqli->query ("SELECT c.id AS cid, s.id, s.name FROM categories AS c LEFT JOIN snippets AS s ON s.category=c.id WHERE c.live=1 ORDER BY c.name, s.name")
or die (mysqli_error ($mysqli));
$sub = $subNavQuery->fetch_object (); // pre-reading one record
while ($nav = $navQuery->fetch_object ()) {
echo '<li>';
echo ''. $nav->name .'';
echo '<ul>';
while ($sub->cid == $nav->id) {
echo '<li>';
echo ''. $sub->name .'';
echo '</li>';
$sub = $subNavQuery->fetch_object ();
}
echo '</ul>';
}
It should print completely the same code as your example
$navQuery = $mysqli->query("SELECT t1.id AS cat_id,t1.slug,t1.name AS cat_name,t2.id,t2.name
FROM categories AS t1
LEFT JOIN snippets AS t2 ON t1.id = t2.category
WHERE t1.live=1
ORDER BY t1.name ASC, t2.name ASC") or die(mysqli_error($mysqli));
$current = false;
while($nav = $navQuery->fetch_object()) {
if ($current != $nav->cat_id) {
if ($current) echo '</ul>';
echo ''. $nav->cat_name .'<ul>';
$current = $nav->cat_id;
}
if ($nav->id) { //check for empty category
echo '<li>'. $nav->name .'</li>';
}
}
//last category
if ($current) echo '</ul>';