I have 2 tables Category and Product
category
id name
1 categoryone
2 categorytwo
product
id categoryid product
1 1 P1
I have a dropdownlist that displays the category , but if any category is present in product table then it should get displayed as a pre selected value from dropdown list, and other categories should get displayed normally
<?
$category="SELECT * FROM `category` ";
$resultcategory = mysqli_query($con, $category);
if(mysqli_num_rows($resultcategory)>0)
{
while($rowcategory = mysqli_fetch_assoc($resultcategory))
{?>
<option value="<? echo $rowcategory['id']; ?>"><? echo $rowcategory['name']; ?></option>
<?}
}
?><?
$category="SELECT * FROM `category` ";
$resultcategory = mysqli_query($con, $category);
if(mysqli_num_rows($resultcategory)>0)
{
while($rowcategory = mysqli_fetch_assoc($resultcategory))
{?>
<option value="<? echo $rowcategory['id']; ?>"><? echo $rowcategory['name']; ?></option>
<?}
}
?>
Can anyone tell how it can be done
First you will need to rebuild your select string to something like this:
$category = "SELECT category.*, product.categoryid".
"FROM category, product".
"WHERE category.id= product.categoryid";
And then add a check in PHP code to see if they match like this
while($rowcategory = mysqli_fetch_assoc($resultcategory))
{
<option value="<?php echo $rowcategory['id']?>" <?php if ($rowcategory['id'] == $rowcategory['categoryid']): ?> selected="selected" <?php endif; ?>></option>
}
There is probably a million of syntax errors in my code, but idea should be clear.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.