I want to show the sub category for the selected option, I tried using an approach, it was successful, but due to the foreach loop, the category names used to repeat it self as I used to select the options. I am trying to figure this out since 2 weeks already. Help will be really appreciated on the said issue. Please help me out on this one.
Database Table Entries:
As you can see below, I have created two tables, one for the menu items and the other one for the sub categories. They are kind of interlinked as the ID
of the Sub Category Table
is same as the SubCategoryID
of the Menu Table
, so I can sort it out and categorize it further in the future.
Menu Table
ID SubCategoryID ItemName ItemDescription
1 1 Bottled Water Test
2 1 Aerated Beverages Test
3 2 Virgin Mojito
Sub Category Table
ID CategoryID SubCategoryName
1 1 Customary Selections
2 1 Mocktails
3 1 Fresh Fruit Juices
Index.php:
This is the front end on where the options are displayed, as per the user’s selection, the value of the item selected will be posted forward to the Sample.php. The values posted are, SubCategoryID
, ItemName
and the ItemDescription
.
<?php
include_once 'dbh.php';
$query = "SELECT * FROM menu;";
$result = mysqli_query($conn, $query);
?>
<form action="generate.php" method="post">
<?php while($row = mysqli_fetch_array($result)) { ?>
<label><?php echo $row['ItemName'];?></label>
<input type="checkbox" value="<?php echo $row['SubCategoryID'] . "-" . $row['ItemName'] . "-" . $row['ItemDescription'];?>" name="data[]" />
<?php } ?>
<button type="submit" class="btn btn-md btn-outline-primary btn-block" style="border-radius: 0px;">Generate PDF</button>
</form>
Sample.php:
The data values posted, are further exploded, so I can style and align the individual values, and all this is enclosed inside the foreach loop.
<div class="root">
<?php foreach ($data as $value) { list($item_sub_category, $item_name, $item_description) = explode('-', $value, 3); { ?>
<div class="main">
<span><?php echo $item_name;?><br/></span>
<span><?php echo $item_description;?></span>
</div>
<?php }} ?>
</div>
My Method:
I was able to get the category according to the assignment, but as it was enclosed within the foreach statement, it was getting repeated every time along with the menu items. Below is the code which I used in the Sample.php.
<?php
include_once 'dbh.php';
$id = $item_sub_category;
$query1 = "SELECT * FROM sub_category WHERE sub_category.id = '$id'";
$result1 = mysqli_query($conn, $query1);
$rows1 = mysqli_fetch_array($result1);
?>
<span><?php echo '---' . $rows1['SubCategoryName'] . '---';?><br/></span>
Output Received:
Output Expected:
Thanks a lot for your time.