I try to create a menu system and within that menu show whatever there is in MySQL based on one column!
Currently, I can add products from my admin panel and it will be added into MySQL database. When I add a product, I can give this product a brand name i.e. diesel, levi, etc.
Now I know how to show the contents of the database in MySQL in a PHP file by using SELECT brand FROM products ...
, but this will show all the duplicated brands in my menu (e.g. 3 levi's, 6 diesels) and it will show them like:
levi
levi
levi
Diesel
Diesel
Diesel
Diesel
But I only 1 need of each. How can I do that?
How can I link the diesel category only to products that have that brand? For instance, if someone clicks on the diesel category, php will only show products that have the diesel brand.
These are fairly simple relational database questions.
1; Use DISTINCT
with your query like
SELECT DISTINCT `brand` FROM `products`;
2; You would need to use a WHERE
clause, based on a parameter that you pass into category.php
somehow. We can't really help you without existing code, but this should probably be what a file like category.php
would be doing anyway.
That said, your brands should really be contained within a separate table and linked to from your products (probably one-many relation, one product can have one brand but a brand can have many products). You should really look up some database design concepts before continuing with your project, in my opinion.
Here's a very simple diagram of how your relationship would work:
Rather than querying products
for your brands, you would simply SELECT name FROM brand
to get a list of your brands.
Then, passing in your brand_id
to category.php
, you can get the products like so SELECT * FROM product WHERE brand_id = 1
.
You need to use a bit of SQL.
To get the different brands:
'SELECT DISTINCT brand from products'
To get the products for a specific brand
'SELECT products WHERE brand = "diesel"'
Be careful when writing the second query to ensure the user can't enter deliberately harmful data. Use prepared statements (PDO / mysqli), like:
$stmt = $dbh->prepare('SELECT products WHERE brand = :brand');
$stmt->bindParam(':brand', $brand);
I'd echo the other answer and say you probably want to design your database a bit and work out what the data is and how it relates to other pieces of data.
Question 1: Your query should be this:
Select distinct brand from products
Question 2 :
You should send the brand to category.php page:
For example the link should be like this:
category.php?brand=disel
Then on category.php page you should change your query somehow like this:
if(isset($_GET['brand']))
mysql_query("select * from products where brand='".$_GET['brand']."'");
else
mysql_query("select * from products");
and it is better to send your brand id instead of brand string to category.php for the query has better performance.