简体   繁体   中英

PHP: Retrieve all possible options within a dropdown and select option for specific record

I am still really new to PHP, I am creating a page for updating a specific record. I have passed an ID into the URL of the page, and using the ID for getting specific data for that record.

The trouble I am having is with dropdown lists. I want to pull back all possible options for that dropdown (which comes from a different table) and I have this sorted.

$status_sql = "SELECT DISTINCT AssetStatus.AssetStatusTitle AS HardwareAssetAssetStatusTitle, HardwareAssetAssetStatusID FROM HardwareAsset INNER JOIN AssetStatus ON (AssetStatus.AssetStatusID = HardwareAsset.HardwareAssetAssetStatusID) ORDER BY HardwareAssetAssetStatusTitle ASC";
$status = sqlsrv_query($database_connection, $status_sql);
while($status_option = sqlsrv_fetch_object($status)){
    echo "<option value='$status_option->HardwareAssetAssetStatusID'>".$status_option->HardwareAssetAssetStatusTitle."</option>";
}

The issue comes when i want to have an option already selected for that record. I know to get the specific option i need the following:

$status_sql = "SELECT DISTINCT AssetStatus.AssetStatusTitle AS HardwareAssetAssetStatusTitle, HardwareAssetAssetStatusID FROM HardwareAsset INNER JOIN AssetStatus ON (AssetStatus.AssetStatusID = HardwareAsset.HardwareAssetAssetStatusID)  WHERE HardwareAssetID = '".$HardwareAssetID."'";

but how do i combine these both together? Having the selected option, selected on load by default, and all other options available when opening the dropdown.

I have spent a fair amount of time searching online, but I dont think I am searching for the right thing, as I havent really turned anything up. Any help appreciated.

You don't have to modify the original SELECT query and put WHERE clause in it. Simply change your while loop in the following way,

while($status_option = sqlsrv_fetch_object($status)){
    $output = "<option value='$status_option->HardwareAssetAssetStatusID'";
    if($status_option->HardwareAssetAssetStatusID == $HardwareAssetID){
        $output .= " selected='selected'";
    }
    $output .= ">".$status_option->HardwareAssetAssetStatusTitle."</option>";
    echo $output;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM