Hi I am new in php and for my study project trying to resolve some challenges
I have 3 tables "products", "categories", "product_to_categories"
products table:
product_id product_name product_price product_img product_link date
1 item1_name item1_price item1_img item1_link item1_date
2 item2_name item2_price item2_img item2_link item2_date
categories table:
category_id category_name
1 category1_name
2 category2_name
3 category3_name
and product_to_categories table:
relation_id product_id category_id
1 product1_id category1_id
2 product1_id category2_id
3 product2_id category1_id
4 product2_id category3_id
I am trying to get 2 things:
- write a list of all products together with the all categories names (no ids) they belong to.
- list only those products that belong to the given categories
Unfortunately, I don't know how to approach this.
show_products.php:
<?php
$per_page=100;
if(isset($_GET['page'])){
$page = $_GET['page'];
}else{
$page=1;
}
$start_from = ($page-1) * $per_page;
$get_products = "SELECT * FROM products ORDER BY 1 DESC LIMIT $start_from,$per_page";
$run_products = mysqli_query($conn,$get_products);
while($row_products=mysqli_fetch_array($run_products)){
$pro_id = $row_products['product_id'];
$pro_name = $row_products['product_name'];
$pro_price = $row_products['product_price'];
$pro_img = $row_products['product_img'];
$pro_link = $row_products['product_link'];
$pro_date = $row_products['date'];
echo "
<tr>
<td style='width: 70px'>$pro_id</td>
<td><img src='../p_img/$pro_img' style='width:70px;'></td>
<td>$pro_name</td>
<td>ok. $pro_price zł</td>
<td>$pro_link</td>
<td></td>
<td>$pro_date</td>
</tr>
";
}
?>
JOIN. The names of the fields even allow MySQLsNATURAL JOIN, which is the easiest way of connecting tables.