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.
Related
I have two tables called mg_product and mg_product_user_property.
In mg_product there are 3 columns: id, title, price as
In mg_product_user_property table product_id corresponds with id column in mg_product table.
So my goal is to get the value of property_id of "15", which in the picture above will be "Mediatek".
This is my SQL:
$sql = "SELECT *
FROM mg_product AS products
INNER JOIN mg_product_user_property AS properties
ON products.id = properties.product_id
WHERE title LIKE '%$search%')";`
PHP:
$resultSet = DB::query($sql);
if ($resultSet->num_rows > 0) {
while ($rows = $resultSet->fetch_assoc()) {
$title = $rows['title'];
$price = $rows['price'];
}
} else {
$output = "No results";
}
Now I need to assign to a php variable the value of property_id=15 so I will be able to print "Mediatek" on my website. How can I achieve that? Sorry for my English.
You are pretty close to what you want, but a couple things are going to either be a mess, or unwanted. So, since there are different ways one can go with this, I will only present a very stripped example (and am INTENTIONALLY leaving out a bunch of code here).
You may not want to do a JOIN like that in the initial search, as for each property, it will also return another of the same product. So looping through that will result in dozens of the same product.
However, if _ALL_YOU_WANT_ is to show the Product Title, Price, and Property 15... you can reduce some headwork with a simpler query:
SELECT p.title, p.price, pr.value
FROM mg_product AS p
LEFT JOIN mg_product_user_property AS pr
ON p.id = pr.product_id AND pr.property_id = 15
WHERE p.title LIKE '%$search%'
The LEFT JOIN means if the property doesn't exist, it will still return the product. But with an empty property value. And this should not return dozens of the same product for every other property in the table.
--
The OTHER way you could go about doing it, using the SQL query you already have (and the dozens of results of the same product it will return), you can alter your php loop like so:
$found_products = array();
while ($row = $resultSet->fetch_assoc()) {
if ($row['property_id'] == 15) {
$found_products[$row['product_id']] = array(
'title' => $row['title'],
'price' => $row['price'],
'prop' => $row['value']
);
}
}
// now you have a clean array of found products that have the property
--
Also I am forced to point out that you should use a prepared statement here, replacing inserting $search directly into the code. But showing you all of how to do that is beyond the scope of this question/answer.
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";
}
I have category table which stores all category info [parent and child both] , category_child table which stores parent and child category relation, and product_category table which stores relation between child_category and product.
category - All Category {cid, cname, isParent, status} column.
category_child - Realtion {parent_id, child_id}.
category_product - Relation {product_id, child_category_id}
product - All product details {pid, pname, pimage, pprice,pstock}
I am displaying all Parent Category Link in Front page. Now, Whenever any person will click on parent category Link, I want to display 4 product information from each child category of parent category.
here is my code, which is horrible at the moment, and i am looking for some help in minimising it as much as possible.
$fetchChild = $mysqli->query("SELECT child_id from category_child where parent_id='".$mysqli->real_escape_string($pid)."'");
$listchild = array();
if($fetchChild->num_rows > 0) {
$n = 1;
while($storeChild = $fetchChild->fetch_assoc()) {
$listchild['child_id'][$n] = $mysqli->query("SELECT product_id from category_product where child_category_id='".$mysqli->real_escape_string($storeChild[$n])."'");
if($listchild['child_id'][$n]->num_rows > 0) {
$i = 1;
while($storeMore = $listchild['child_id'][$n]->fetch_assoc()) {
$listchild['product_id'][$i] = $mysqli->query("SELECT pid, pname, pimage, pprice, pstock from product where pid='".$mysqli->real_escape_string($storeMore[$i])."'");
if($listchild['child_id'][$n]['product_id'][$i]->num_rows > 0) {
$me = 1;
while($smeLast = $storeMore[$i]->fetch_assoc()) {
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pid'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pname'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pimage'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pprice'];
$listchild['child_id'][$n]['product_id'][$i]['pid'] = $smeLast['pstock'];
$me++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php?error=Something+Went+Wrong+We+are+Fixing+it" />';
}
$listchild['product_id'][$i]->free();
$i++;
}
}
$listchild['child_id'][$n]->free();
$n++;
}
} else {
echo '<meta http-equiv="refresh" content="0; url=index.php" />';
}
$fetchChild->free();
Kindly help in minimizing nested while and query in my code.
Thanks
If you want, you can put everything into one SQL query using JOIN statement.
SELECT `category`.*, `product`.* FROM `product`
LEFT JOIN `category_product` ON `category_product`.`product_id` = `product`.`pid`
LEFT JOIN `category_child` ON `category_child`.`child_id` = `category_product`.`child_id`
LEFT JOIN `category` ON `category`.`cid` = `category_child`.`child_id`
WHERE `category_child`.`parent_id`='".$mysqli->real_escape_string($pid)."'
But I don't think it's the best solution.
PS. By the way, there is no LIMIT of 4 products per child category in your code, so I haven't put it either.
You can reduce all your queries to one query with JOINS. Using joins will allow you to return results from one table (e.g. product) basing on the conditions provided in another table or tables (e.g. category_product, category_child).
Read more about joins somewhere at Stack Overflow or browse some other resources. For example http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html .
You should never use SQL query in a loop! It is very slow, you can overload the sql server etc...
Your database structure is bad. If you want to store hiearchical tree there are better options:
Tree 1 level:
1A2
Tree 2 level:
1A6
2B3 4C5
Tree 3 level:
1A12
2B7 8C9 10D11
3E4 5F6
You have a left and a right value by each node, and you can have the parent id too. You can check whether a node is leaf or branch if you check the difference of the right-left. By leaves it is one. You can check whether a leaf is under a branch if its left is bigger than the left of the branch and its right is smaller than the right of the branch. etc... This structure is described on several sites, for example here: nested set model
After you transformed your model to nested set, you can use a simple sql to ask for your products. Something like this:
SELECT
p.*
FROM
categories c, categories b, products p, product_categories pc
WHERE
b.category_id = ?
AND
c_category_id <> b.category_id
AND
c.category_left BETWEEN b.category_left AND b.category_right
AND
c.category_right - c.category_left = 1
AND
c.category_id = pc.category_id
AND
p.product_id = pc.product_id
This is good for beginning, your code will contain group by, limit, etc... because you want to ask only a single product per category... (or you can simply use order by rand() and limit 4 ...)
You should use prepared statements instead of manual escaping... http://php.net/manual/en/mysqli.prepare.php
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>';
I'm coding in PHP/MySQL and have the following query to fetch products and product group data:
SELECT products.id,products.name,product_groups.id,product_groups.name
FROM products
INNER JOIN product_groups
ON products.id=product_groups.id
WHERE products.name LIKE '%foobar%'
ORDER by product_groups.id ASC
So this query fetches products and orders them by product group. What I would like to have is to display product_groups.name just once for each product grouping. So even if I have ten shoe products, the group name "Shoes" is only displayed once.
I'm using the following PHP to print out the results:
while ($data = mysql_fetch_array($result))
If you want it done in the MySQL query, it is honestly more trouble than it's worth. For one, the syntax is really wonky (as I recall) to have a group name listed at the top of each grouping. And the results are still treated as rows, so the group name will be treated like a row with all the other columns as Null, so you won't really save any time or effort in the PHP script as it has to do an if statement to catch when it hits a group name instead of the group data.
If you want it done by the PHP while loop, Johan is on the right track. I use the following for a similar situation:
$result = $sql->query($query);
$prev_group = "";
while($data = $result->fetch_assoc()){
$curr_group = $data['group'];
if ($curr_group !== $prev_group) {
echo "<h1>$curr_group</h1>";
$prev_group = $curr_group;
}
else {
echo $data;
.....
}
Obviously the echo data would be set up to echo the parts of the data the way you want. But the $prev_group/$curr_group is set up so that the only time they won't match is when you are on a new group and thus want to print a header of some sort.
while($data = mysql_fetch_assoc($result)){
if($data['product_groups.name'] != $groupname){
echo "Groupname: ".$data['product_groups.name']."<br />";
$groupname = $data['product_groups.name'];
}
echo "ID: ".$data['products.id']."<br />";
echo "Name: ".$data['products.name']."<br />";
}
Maybe you can do like this!?