Reputation: 95
I need some help with this php file.
I'll explain what I need to do firstly:
I have main categories of products. When you click on a category you are then taken to a page with the subcategories for the clicked category, this part works fine. I now need it so that when you click on a subcategory, all the products for that subcategory are loaded into a div on the same page (using php with a refresh....)
I will post my code and comment it explaining the issues.
<?php
include 'connect.php';
$cat_id = intval($_GET['category']); //GETS THE CAT_ID OF THE CLICKED CATEGORY LINK
$sql = mysqli_query($link, "SELECT * FROM subcategories WHERE cat_id = $cat_id AND
status = 1");
$output = '';
while($row = mysqli_fetch_array($sql)){
$data = $row['image'];
$file = substr($data, strpos($data, "/") + 1);
$output .= "<div class='subcats'>";
$output .= "<a href='cats.php?subcategory=" . $row['subcat_id'] . "'>
<img src='$file' />"; //WHEN I CLICK ON A SUBCAT, I GET AN ERROR OF
'UNDEFINED' FOR CATEGORY. NO CATEGORY IS BEING CLICKED. HOW DO I GET IT TO LOOK FOR A
CATEGORY ONLY IF ONE IS CLICKED?
$output .= "<div class='maincatheadings'>{$row['subcategory']}</div>";
$output .="</a>";
$output .= "</div>";
}
echo $output
?>
Upvotes: 0
Views: 444
Reputation: 9331
You need the category ID to show the list of subcategories, so skipping the category ID entirely isn't an option. I see two ways to solve this problem:
category
as well as subcategory
on each of the links.category
is set, but subcategory
exists, you retrieve the category from the database by searching the parent of the selected subcategory.Option 2 is much more solid than 1, because this cannot be manipulated into faulty parameter sets. (People could manipulate the URL and cause weird stuff to happen, if you don't make sure all necessary checks are done first.)
I would still consider changing the code, because right now you have no error handling in case the submitted category ID doesn't exist.
Upvotes: 2
Reputation: 1937
Because on the second click you are reloading with new values, and category isn't in the new set.
$output .= "<a href='cats.php?subcategory=" . $row['subcat_id'] . "'>
Will redirect from cats.php?category=XXXX to cats.php?subcategory=YYYY
This should do the work in your example :
$output .= "<a href='cats.php?category=". $_GET['category'] ."&subcategory=" . $row['subcat_id'] . "'>
Will redirect from cats.php?category=XXXX to cats.php?category=XXXX&subcategory=YYYY
And this should handle the "anything is selected" case if you need to :
$cat_id = intval(isset($_GET['category']) ? $_GET['category'] : 0);
Upvotes: 2
Reputation: 439
use a simple check prior to while loop, it result count is 0 than go to find products and than assign it to results:
$result = $mysqli->query($sql_quer);
$num_rows = $result->num_rows;
if($num_rows === 0)
{
$sql = mysqli->query("SELECT * FROM products WHERE cat_id = $cat_id AND
status = 1");
}
Upvotes: 0