i was given help previously on how to join multiple tables together to get this navigation list to work, as you can see i have done this, but now i am trying to output the navigation in my list, but it is duplicating the top and bottom categories based on how many products are in those categories: this is previous link that shows my table setup:
Joining 2 tables with foreign key id
Here is my code trying to echo out the navigation correctly.
try
{
$result = $pdo->query('SELECT product.*, bottom_category.bottom_name, top_category.top_name
FROM product
INNER JOIN bottom_category ON bottom_category.id = product.bottom_category_id
INNER JOIN top_category ON top_category.id = bottom_category.top_category_id
ORDER BY top_category.id,bottom_category.id');
} // end try
catch (PDOException $e)
{
echo 'There was a error fetching the products.' . $e->getMessage();
exit();
} // end catch
$products = array();
foreach ($result as $row)
{
$products[] = array('top_name' => $row['top_name'],
'bottom_name' => $row['bottom_name']);
}
?>
<div class="sidebar">
<h4 class="sidebar-header">Select Products</h4>
<form class="nav-search-form">
<input type="search" name="search" placeholder="Search products">
</form>
<nav class="sidebar-links">
<ul>
<li><a id="red" href="/semtronics/index.php">New Products</a></li>
<?php
foreach ($products as $product):
?>
<li><?php echo htmlspecialchars($product['top_name']);?>
<ul>
<li><?php echo htmlspecialchars($product['bottom_name']);?></li>
</ul>
</li>
<?php endforeach; ?>
</ul>
</nav>
</div><!-- sidebar -->
Now it all works the only problem is it is duplicating the navigation list based on how many products are linked to that category.
I think you need another solution for this task.
You don't need product here
Query what you need is:
select bottom_category.name as bottom_name, top_category.name as top_name
from bottom_category
inner join top_category on top_category.id = bottom_category.top_category_id
order by top_category.id, bottom_category.id
I was thinking that you need something from product table in your code, but if no - use SQL query above.
Or you need data from product table ?
If you need from product you can run
select bottom_category.name as bottom_name, top_category.name as top_name
from product
inner join bottom_category on bottom_category.id = product.bottom_category_id
inner join top_category on top_category.id = bottom_category.top_category_id
group by product.bottom_category_id
order by top_category.id, bottom_category.id
But be careful, you don't know which row from product would be used in this case
Related
I very recently (as in, this week) started learning PHP and am doing a practice task.
(Therefore, apologies in advance, if I sound like I don't know what I'm talking about, that is true)
Here is a crude schematic of my tables:
I have a main table products, and there are 3 planned product types (book, disc, furniture), and each type has a special attribute, with their own tables. (size for discs, weight for books etc.)
So far through testing, I've managed to query out the object from my products table each into their separate bootstrap card components. What I am trying to accomplish now is to add the special attributes to their respective object cards.
This is where i've reached a dead end. The idea I have is to first create a seperate array $printtocard, then call all the products table records by type, then run a foreach through all the found records, and then run a switch inside the foreach where i check the product types and run cases based on type, which create new objects based on the linked table data, and add each of them to the $printtocard array.
Afterwards the plan is to call the array in the code that later outputs the objects.
Here is my code so far:
Main php code
class products {
var $arrayy;
var $sql;
var $typepr;
protected function get_prod($conn1){
$printtocard = array();
$call_type = 'SELECT type FROM products ORDER BY id';
$type_res = mysqli_query($conn1, $call_type);
$type_arr = mysqli_fetch_all($type_res, MYSQLI_ASSOC);
$this->typepr = $type_arr;
return $this->typepr;
foreach($typepr as $xxx){
switch($xxx){
case "disc":
/* $disc_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "book":
/* $book_ */$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_weight AS a ON p.id = a.product_id;';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
case "furniture":
/* $furniture_ */$sql = 'SELECT p.sku, p.name, p.price, a.height, a.width, a.length, FROM products AS p INNER JOIN attr_dims AS a ON p.id = a.product_id';
$val_res = mysqli_query($conn1, $sql);
$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$printtocard[] = $val_arr;
return $this->printtocard;
break;
}
}
//$sql = 'SELECT p.sku, p.name, p.price, a.value FROM products AS p INNER JOIN attr_size AS a ON p.id = a.product_id;';
//$call2 = 'SELECT sku, name, price FROM products ORDER BY id';
//$val_res = mysqli_query($conn1, $sql);
//$val_arr = mysqli_fetch_all($val_res, MYSQLI_ASSOC);
$this->arrayy = $printtocard;
return $this->arrayy;
}
public function get_prod2($conn1)
{
$this->get_prod($conn1);
}
}
$fff= new products;
$fff->get_prod2($conn);
$sss= $fff->arrayy;
Snippet of the webpage code where I autogenerate the cards:
<div class="container">
<div class="row">
<?php
foreach($sss as $value){ ?>
<div class="col s6 md2">
<div class="card cardstyle z-depth-0">
<div class="card-content center">
<?php echo htmlspecialchars($value['sku']); ?>
<div>
<?php echo htmlspecialchars($value['name']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['price']); ?>
</div>
<div>
<?php echo htmlspecialchars($value['value']); ?>
</div>
</div>
<div class="card-action right-align">
<a class="brand-text" href="#"> more info </a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
The error message I currently get:
Warning
: Invalid argument supplied for foreach() in
C:\xampp\htdocs\uzdevumi\scandi_uzdevumi_kristianskonters\productlist\productlist.php
on line
108
A number of pointers
1. Its better to define your variables at the top depending on your intentions later (protected, private or public)
protected $arrayy;
protected $sql;
protected $typepr;
The return just before your "foreach" loop renders your loop pointless because it stops your function there and returns what you have.
return $this->typepr;
In connection to my previous point, you seem to think that "return" does some concatenation for you as shown by each "case" you have in your switch. No it does not it exits your function back to the calling scope.
return $this->printtocard;
The warning you have at the end means what it says, you are providing the "foreach" loop with an invalid argument. In other words it does not exist, thankfully its php (dynamically typed). But the problem is its undefined (has not value). Maybe its a typo and you wanted to loop through the array variable you got from sql calls.
foreach($typepr as $xxx)
Cross check typos and I did not get to check your html.
i have two tables Category and sub category in php i want to show them in accordion
but my code is not working please help. below are the columns on two tables.
category = c_id, category_name.
sub_category = sub_cat_id, sub_cat_name, c_id
<?php
$sql="select * from category";
$res=mysqli_query($con,$sql);
while($row=mysqli_fetch_array($res))
{
?>
<li class="subMenu"><a> <?php echo $row["category_name"]?> [840] </a>
<ul style="display:none">
<?php
$sql1="SELECT * FROM category INNER JOIN sub_category ON
sub_category.cat_id = category.cat_id;";
$res1=mysqli_query($con,$sql1);
while($row1=mysqli_fetch_array($res1))
{
?>
<li><a href="products.html"><i class="icon-chevron-right"></i><?php echo
$row1["sub_cat_name"]?></a></li>
<?php } // while loop
?>
</ul>
</li>
<?php
}
Hi just used this query in my second while loop and now its working fine
Query $sql1="select * from sub_category WHERE cat_id = ".$row['cat_id']."";
I know this question has been asked 1000s of times before but please bear with me as I have a slightly different scenarion.
Basically I have 2 MYSQL tables that I join (one called category and the other is products) and I create categories and subcategories menu in my PHP page using the following code:
<?php
$subcategories="";
$sql3="SELECT products.di_cat, GROUP_CONCAT(products.di_name) as di_name
FROM products LEFT JOIN category ON products.di_cat=category.names
GROUP BY products.di_cat";
$query3 = mysqli_query($db_conx, $sql3);
$existCount3 = mysqli_num_rows($query3);
if ($existCount3!=0) {
while($row3 = mysqli_fetch_array($query3, MYSQLI_ASSOC)){
$make_names = $row3["di_cat"];
$make_model = $row3["di_name"];
$subcategories = explode(",",$make_model);
print '<div class="col-md-3">
<span class="mega-menu-sub-title">'.$make_names.'</span>
<ul class="sub-menu">
<li>
<ul class="sub-menu">';
foreach($subcategories as $sub){
print '<li>'.$sub.'</li>';
}
print '</ul></li></ul></div>';
}
}
?>
This works fine and as it should.
Now I have a column in my products table called url.
This column is for creating clean URLs and the content of is basically the products names without any spaces or special characters.
I would like to use this in my code above but I don't understand why every time I try to use the follwoing code, I only get 1 subcategory/product from each category being displayed in my PHP page even though I have 100s of products under each category!
This what i tried:
<?php
$subcategories="";
$sql3="SELECT products.di_cat, products.url, GROUP_CONCAT(products.di_name) as di_name
FROM products LEFT JOIN category ON products.di_cat=category.names
GROUP BY products.di_cat";
$query3 = mysqli_query($db_conx, $sql3);
$existCount3 = mysqli_num_rows($query3);
if ($existCount3!=0) {
while($row3 = mysqli_fetch_array($query3, MYSQLI_ASSOC)){
$make_names = $row3["di_cat"];
$make_model = $row3["di_name"];
$make_url = $row3["url"];
$subcategories = explode(",",$make_url);
print '<div class="col-md-3">
<span class="mega-menu-sub-title">'.$make_names.'</span>
<ul class="sub-menu">
<li>
<ul class="sub-menu">';
foreach($subcategories as $sub){
print '<li>'.$sub.'</li>';
}
print '</ul></li></ul></div>';
}
}
?>
Can someone please advice on this issue?
Any help would be appreciated.
So I'm making a portfolio website where I can post and edit blogs.
I'm making the blog edit page and I'm having trouble with combining two table together.
The first table is for the blogs and the second table holds all the different blog categories.
Here's how I'm getting the blog posts:
$qStr = "SELECT post_title, post_content, post_description, post_active, category_id FROM posts WHERE post_id = {$post_id}";
Here's how I'm getting the blog categories:
$qStr = "SELECT category_name FROM categories WHERE category_id = {$category_id}";
So in my edit blog post page I have a dropdown box that I need to show which category that blog post is in, and be able to change it. I have a category_id in my blog table. My question is how do I get the dropdown to show which category the post is under?
Right now my drop down code looks like this (note: Right now I'm just populating the dropdown with all the categories)
<div class="form-group">
<label for="categorySelect" class="col-lg-2 control-label">Category</label>
<div class="col-lg-3">
<select class="form-control" id="categorySelect">
<?php
foreach ($categories as $cat) {
echo("<option>{$cat['category_name']}</option>");
}
?>
</select>
</div>
</div>
You need to set up the selected attribute for select (option) element, something like this:
<?php
foreach ($categories as $cat) {
if ($cat['category_name'] == $category_of_your_post)
echo "<option selected=\"selected\">{$cat['category_name']}</option>";
else
echo "<option>{$cat['category_name']}</option>";
}
?>
BTW, I think that you have the wrong queries (if I understood correctly your question). Basically you need to retrieve the category_id of your post and perform an equality question against the array of categories:
$qStrBlog = "SELECT post_title, post_content, post_description, post_active, category_id FROM posts WHERE post_id = {$post_id}";
$qStrCat = "SELECT category_id, category_name FROM categories";
And then:
<?php
foreach ($categories as $cat) {
if ($cat['category_id'] == $blog_data['category_id'])
echo "<option selected=\"selected\">{$cat['category_name']}</option>";
else
echo "<option>{$cat['category_name']}</option>";
}
?>
You have two options:
Add a selected attribute with an if-condition in the foreach loop:
foreach ($categories as $cat) {
echo '<option';
if ($cat['category_id'] == $post['category_id']) echo ' selected';
echo '>'.$cat['category_name'].'</option>';
}
Or use an INNER JOIN on the post SELECT query:
$qStr = "SELECT p.post_title, p.post_content, p.post_description, p.post_active, p.category_id, c.category_name FROM posts INNER JOIN categories c ON c.category_id = p.category_id WHERE post_id = {$post_id}";
and throw the first option element as the "default currently selected" option:
<select class="form-control" id="categorySelect">
<option value="<?= $post['category_id'] ?>"><?= $post['category_name'] ?> (current)</option>
<?php
foreach ($categories as $cat) {
echo("<option>{$cat['category_name']}</option>");
}
?>
</select>
I've made the assumption that you've correctly loaded your result from the first SELECT query into $post. Note that if it's possible to not set a Category to a Post, you should use LEFT JOIN instead and wrap the first option element output contingent on $post['category_id'] not being empty.
Ok so i am having a problem with figuring this problem out. I have a dynamic page that has records pulled out of a mysql database. The php code works great. The code is below
$catagory = $_GET['type'];
$query = "SELECT p.name, p.price, pc.quantity, p.image, p.descr FROM products ... where category_name = $catagory ";
$result = mysql_query($query);
$related = array();
while($row_r = mysql_fetch_assoc($result)){
$related[] = $row_r;
}
later on down the page I loop through them
<div class="main-blue">
<div class="blue-items">
<?php foreach ($related as $row_r) { ?>
<span class="digit"><span class="digit-r"><?php print $row_r["quantity"] ?></span></span>
<h3><?php print $row_r['name'] ?></h3>
.....
The problem is I have a
<div class="dropdown">
<ul>
<li>Grocery</li>
<li>Pizza</li>
<li>Quick Service</li>
<li>Retail</li>
<li>Salon</li>
<li>Bar</li>
</ul>
I need to be able to select one of the dropdowns like for example Bar I need to regrab the record from mysql and make the page load with the records for Bar without refreshing .
like
$catagory = "Bar";
$query = "SELECT p.name, p.price, pc.quantity, p.image, p.descr FROM products ... where category_name = $catagory ";
You need to use some sort of AJAX implementation to get this to work.
It will allow Js to query your PHP script to get a table or new JSON data to repopulate the table.
It doesn't look like you have any jQuery at the moment, give it a go to start with!
This question is very similar