tithij
tithij

Reputation: 29

populate a drop down from a table and then set the selected option from another table

I have a table of order statuses that a sales order can have; the statuses are not necessarily sequential. I can get these statuses into a drop down using the following:

$sql1 = 'SELECT * FROM `mjj_order_status` ORDER BY Order_status_name DESC';
$result_order_status = mysql_query($sql1);

echo '<select name="Order_status">';
while ($row = mysql_fetch_array($result_order_status)) {
    echo '<option
    value="'.$row['Order_status_ID'].'">'.$row['Order_status_name'].'</option>';
}
echo '</select>';

My problem occurs when I try to fetch the order data from the DB, and then set the dropdown list to that order's status. I can run the query to get the order status that should be selected, but am not sure how to code how to apply this information. The query to get the order status ID is:

SELECT Order_status FROM `mjj_orders` WHERE Order_ID = $_POST['Order_ID']

I have searched (I think comprehensively) and I haven't found a feasible answer or - to be fair - one that I can understand.

(I have found a question similar to this one, but I am unsure how to get them to elaborate... selected item ind dropdown when editing).

Any and all advice would be great. Thanks.

Upvotes: 0

Views: 1292

Answers (2)

Dave
Dave

Reputation: 1001

just drop in some logic checking what status the order you are working on has.

$sql = "SELECT Order_status FROM 'mjj_orders' WHERE Order_ID = ".$_POST['Order_ID']; 
$result=mysql_query($sql); 
$myorder=mysql_fetch_array($result);

$sql1 = 'SELECT * FROM `mjj_order_status` ORDER BY Order_status_name DESC'; 
$result_order_status = mysql_query($sql1); 

echo '<select name="Order_status">'; 
while ($row = mysql_fetch_array($result_order_status)) { 
    if($myorder['Order_status']==$row['Order_status_ID']){
        $selectCurrent=' selected';
    }else{
        $selectCurrent='';
    }
    echo '<option value="'.$row['Order_status_ID'].'" '.$selectCurrent.'>'.$row['Order_status_name'].'</option>';
} 
echo '</select>'; 

Upvotes: 1

Erik
Erik

Reputation: 2264

just mark the option where order_status_id = the id that should be selected with selected. eg. the option that will be selected will look like <option selected value="... like this:

$id_to_select = // Your logic to get the id to select

$sql1 = 'SELECT * FROM `mjj_order_status` ORDER BY Order_status_name DESC';
$result_order_status = mysql_query($sql1);

echo '<select name="Order_status">';
while ($row = mysql_fetch_array($result_order_status)) {
  if($id_to_select == $row['Order_status_ID'])
    echo '<option selected value="'.$row['Order_status_ID'].'">'.$row['Order_status_name'].'</option>';
  else     
    echo '<option value="'.$row['Order_status_ID'].'">'.$row['Order_status_name'].'</option>';
}
echo '</select>';

Upvotes: 0

Related Questions