PHP:一页上多个字段的MSSQL查询

时间:2017-04-27 18:32:39

标签: php sql-server

我是PHP的新手,并且有一个Web表单,我使用PHP从数据库中获取数据。我目前所做的,因为我还没有找到另一个解决方案(尽管我的搜索 - 可能不知道要查找的正确术语),是为我的表单上的每个输入字段单独执行SQL查询。 如下:

            <div class="search-line">
                <div class="search-option">
                    <label>Asset Tag:<i title=""></i></label>

                    <?php

                    $asset_tag_sql = "SELECT HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
                    $asset_tag = sqlsrv_query($database_connection, $asset_tag_sql);

                    ?>

                    <input type="text" id="AssetTag" disabled value="<?php while ($asset_tag_option = sqlsrv_fetch_object($asset_tag)){echo $asset_tag_option->HardwareAssetAssetTag;} ?>" />
                </div>
                <div class="search-option">
                    <label>Serial Number:<i title=""></i></label>

                    <?php

                    $serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
                    $serial_number = sqlsrv_query($database_connection, $serial_number_sql);

                    ?>

                    <input type="text" id="SerialNumber" disabled value="<?php while ($serial_number_option = sqlsrv_fetch_object($serial_number)){echo $serial_number_option->HardwareAssetSerialNumber;} ?>" />
                </div>
            </div>

是否有一段PHP代码执行一个SQL查询,然后用它来获取和回显两个输入字段的值,而不是上面两个?

2 个答案:

答案 0 :(得分:2)

试试这样吗?

<?php
$asset_sql = "SELECT HardwareAsset.HardwareAssetAssetTag,HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'"
$asset_result = sqlsrv_query($database_connection, $asset_sql);
$asset_data = sqlsrv_fetch_object($asset_result);
?>

<div class="search-line">
    <div class="search-option">
        <label>Asset Tag:<i title=""></i></label>
        <input type="text" id="AssetTag" disabled value="<?php echo $asset_data->HardwareAssetAssetTag; ?>" />
    </div>
    <div class="search-option">
        <label>Serial Number:<i title=""></i></label>
        <input type="text" id="SerialNumber" disabled value="<?php echo $asset_data->HardwareAssetSerialNumber; ?>" />
    </div>
</div>

答案 1 :(得分:1)

为什么不从初始查询中选择两个字段,如下所示:

$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber, 
HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE 
HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";