I have two tables: orders and companies. Note that both tables has a company_id
row.
Orders Table:
order_id | order_name | company_id | .....
Companies Table:
company_id | company_name | .....
I have a page with a form that INSERTS data for an order into the orders table in my database. Part of the order is selecting a company from the companies table to go with it, so I use a dropdown for this.
I also have another page with a form that UPDATES that data (an edit page). When I click on the button to bring up the edit page, I'd like to have the previously submitted data in the input fields. With text fields, I just use value="<?php echo $company['whatever']; ?>"
. However, with dropdown menu's I can't figure out how to pre-select the correct option.
Here is my URL structure:
http://website.com/orders.php?page=edit&order_id=1
Here is what I have to create my dropdown menu:
$getOrder = mysqli_query($db, "SELECT * FROM orders WHERE order_id = ".$_GET['order_id']);
$getCompany = mysqli_query($db, "SELECT * FROM companies ORDER BY company_name ASC");
....
<select class="form-control" name="company_id" id="company_id">
<?php
if($getCompany) {
while($company = mysqli_fetch_assoc($getCompany)) { ?>
<option value="<?php echo $company['company_id']; ?>">
<?php echo $company['company_name']; ?>
</option>
<?php }
}
?>
How can I get selected
on the option that's been previously selected?
If $getOrder
has the order details (including company_id
), and $getCompany
has the company details (including company_id
), then you can compare the two.
If they are equal, echo
out selected
as an attribute in the option
, like so:
<select class="form-control" name="company_id" id="company_id">
<?php
if($getCompany) {
//Get company ID from Order
$orderID = $getOrder["company_id"];
while($company = mysqli_fetch_assoc($getCompany)) { ?>
<option value="<?php echo $company['company_id']; ?>"
<?php
//Compare and echo `selected` if they are equal
if($orderId==$company["company_id"]) echo "selected";
?>>
<?php echo $company['company_name']; ?>
</option>
<?php }
}
?>
That code can be cleaned up, however:
<select class="form-control" name="company_id" id="company_id">
<?php
if($getCompany) {
$orderID = $getOrder["company_id"];
while($company = mysqli_fetch_assoc($getCompany)) {
echo "<option value='{$company['company_id']}".($getOrder["company_id"]==$getCompany["company_id"] ? " selected" : null).">{$company['company_name']}</option>";
}
}
?>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments