在下拉列表中显示用户选择

时间:2015-11-26 15:54:00

标签: php html drop-down-menu

用户选择CD后,我试图通过编辑显示用户的选择,以便我在文本框或下拉列表中显示它。如图所示,我可以让Publisher显示在文本框中,但对于下拉列表,它显示为空白。我在选项值中尝试$ CDPub,但它不起作用。

enter image description here

   <form method="get" action="UpdateCD.php">
    <div align="center">  
    <div>Title <input type = "text" name = "CDTitle" value = "<?php echo $CDTitle; ?>" /></div></br>
    <div>Year <input type = "text" name = "CDYear" value = "<?php echo $CDYear; ?>" /></div></br>
    <div>Price <input type = "text" name = "CDPrice" value = "<?php echo $CDPrice; ?>" /></div></br>
    <div>Category <input type = "text" name = "CDCat" value = "<?php echo $CDCat; ?>" /></div></br>
    <div>Publisher <input type = "text" name = "CDPub" value = "<?php echo $CDPub; ?>" /></div></br>
    Publisher 
        <select name="CDPub">
           <option value= " ">
            <?php 
            include 'database_conn.php';            //make db connection
             if (! ( is_object($conn ) && ( get_class( $conn ) == 'mysqli' ))) {
                die("DB connection failure.");
             }
             $rsCDpub = mysqli_query($conn, "SELECT nmc_publisher.pubName FROM nmc_publisher");
             if ( !$rsCDpub ) {
                die("No result from DB query."); //probably invalid SQL, table error
             }
             if ( $rsCDpub->num_rows < 1 ) {  
                die("No rows returned from DB query."); //query runs but nothing is found in DB to match
             }
             while($Catpubresult = mysqli_fetch_array($rsCDpub)){
             echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
             //echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
             }
             ?></br></br>
    <div><input type="submit" value="Update"></div>
    </form>

1 个答案:

答案 0 :(得分:2)

您可以这样做:

 // your code        

 while($Catpubresult = mysqli_fetch_array($rsCDpub)){
    $option = "<option value='{$Catpubresult[0]}'";
    if($Catpubresult[0] == $CDPub){
        $option .= " selected='selected'";
    }
    $option .= ">{$Catpubresult[0]}</option>";
    echo $option;
 //echo "<option value='".$Catpubresult[0]."'>".$Catpubresult[0]."</option>";
 }

 // your code