如何使用Mysql数据填充下拉列表的选定值?

时间:2021-10-24 07:34:14

I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.

我需要sql数据库填充表单输入的值。我的代码适用于所有文本和textarea输入,但我无法弄清楚如何将数据库值分配给下拉列表,例如。 '房产类型'如下。它围绕着“选择选项”来表示数据库中保存的值。

Here is my code:

这是我的代码:

$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");    
$row = $db->sql_fetchrow($result);

echo "<center><font class=\"title\">"._CHANGE_MY_INFORMATION."</font></center><br>\n";
echo "<center>".All." ".fields." ".must." ".be." ".filled."  
<form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\">           
  <table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\">        
    <tr>                
      <td align=\"right\">".Telephone." :</td>                
      <td>
        <input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"> Inc. dialing codes
      </td>        
    </tr>        
    <tr>                
      <td align=\"right\">".Type." ".of." ".property." ".required." :</td>                                          
      <td>Select from list:
        <select name=\"req_type\" value=\"$row[req_type]\">                   
          <option>House</option>                  
          <option>Bungalow</option>                  
          <option>Flat/Apartment</option>                  
          <option>Studio</option>                  
          <option>Villa</option>                  
          <option>Any</option>                  
         </select>  
       </td>          
      </tr>
....

7 个解决方案

#1


5  

using your current code:

使用您当前的代码:

<?php
  $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

  foreach($options as $option) {
    if ($option == $row['req_type']) {
      print '<option selected="selected">'.$option.'</option>'."\n";
    } else {
      print '<option>'.$option.'</option>'."\n";
    }
  }
?>

assuming $row['req_type'] is one of the values in $options. i strongly suggest quoting your array elements (ie $row['req_type'] instead of $row[req_type]. the latter method generates errors under error_reporting(E_ALL)

假设$ row ['req_type']是$ options中的值之一。我强烈建议引用你的数组元素(即$ row ['req_type']而不是$ row [req_type]。后一种方法在error_reporting(E_ALL)下生成错误

you also might want to look at resources such as phpbuilder.com. some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).

您也可以查看phpbuilder.com等资源。有些文章已经过时,但会为您提供有关如何更好地构建代码的一些基础知识。 (例如,将HTML与PHP代码分开,可以帮助您更好地理解这种情况)。

edit: as per the comments, any information displayed should be escaped properly (see htmlentities() for example).

编辑:根据评论,显示的任何信息都应该正确转义(例如,参见htmlentities())。

#2


1  

Nigel,

See the answer with the check mark next to it. It go me start in solving my problem. First I select my data from the table, then I select the data i want display in my dropdown menu. If the data from the primary table matches the data from the dropdown table selected is echoed.

请在旁边用复选标记查看答案。它让我开始解决我的问题。首先,我从表中选择我的数据,然后在我的下拉菜单中选择我想要显示的数据。如果主表中的数据与所选下拉表中的数据匹配,则回显。

$query9 = "SELECT *
       FROM vehicles
       WHERE VID = '".$VID."'
       ";

$result9=mysql_query($query9);
while($row9 = mysql_fetch_array($result9)){
    $vdate=$row9['DateBid'];
    $vmodelid=$row9['ModelID'];
    $vMileage=$row9['Mileage'];
    $vHighBid=$row9['HighBid'];
    $vPurchased=$row9['Purchased'];
    $vDamage=$row9['Damage'];
    $vNotes=$row9['Notes'];
    $vKBBH=$row9['KBBH'];
    $vKBBM=$row9['KBBM'];
    $vKBBL=$row9['KBBL'];
    $vKBBR=$row9['KBBR'];
    $vYID=$row9['YID'];
    $vMID=$row9['MID'];
    $vModelID=$row9['ModelID'];
    $vELID=$row9['ELID'];
    $vECID=$row9['ECID'];
    $vEFID=$row9['EFID'];
    $vColorID=$row9['ColorID'];
    $vRID=$row9['RID'];
    $vFID=$row9['FID'];
    $vDID=$row9['DID'];
    $vTID=$row9['TID'];
}

$query1 = "SELECT * FROM year ORDER BY Year ASC";
$result1=mysql_query($query1);
echo "<select  name='Year'>";
while($row1 = mysql_fetch_array($result1)){
    echo "<option value = '{$row1['YID']}'";
    if ($vYID == $row1['YID'])
        echo "selected = 'selected'";
    echo ">{$row1['Year']}</option>";
}
echo "</select>";

#3


0  

May not be efficient, but it's simple & gets the job done.

可能效率不高,但很简单并完成工作。

$dropdown = str_replace("<option value=\"".$row[column]."\">","<option value=\"".$row[column]."\" selected>",$dropdown);

#4


0  

Thanks Owen. Your code seems perfect but gave lots of php errors. I simplified it to this but just get whitespace as options:

谢谢欧文。你的代码看起来很完美但是给了很多php错误。我把它简化为这个但只是得到空白作为选项:

<td>Select from list: <select name=\"req_type\">        

$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

foreach($option as $option) {  
if ($option == $row[req_type]) {    
    <option selected>$option</option>} 
else {    
<option>$option</option>}};
</select></td>

#5


0  

        <?php
            $result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");    
            $row = $db->sql_fetchrow($result);

            // options defined here
            $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

       ?>     
            <center><font class="title"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />

            <center> All fields must be filled </center> 
            <form name="EditMyInfoForm" method="POST" action="users.php" enctype="multipart/form-data">           
              <table align="center" border="0" width="720" id="table1" cellpadding="2" bordercolor="#C0C0C0">        
                <tr>                
                  <td align="right">Telephone :</td>                
                  <td>
                    <input type="text" name="telephone" size="27" value="<?php echo htmlentities($row['telephone']); ?>" /> Inc. dialing codes
                  </td>        
                </tr>        
                <tr>                
                  <td align="right">Type of property required :</td>                                          
                  <td>Select from list:
                    <select name="req_type">
                  <?php foreach($options as $option): ?>     
                      <option value="<?php echo $option; ?>" <?php if($row['req_type'] == $option) echo 'selected="selected"'; ?>><?php echo $option; ?></option>                  
                  <?php endforeach; ?>
                     </select>  
                   </td>          
                  </tr>

...

oops.. a little too carried away.

哎呀......有点太过分了。

#6


0  

Thanks everyone for all your help. Although I couldn't get any one answer to work it gave me ideas and I have accomplished the job! I ended up going about it a long-winded way but hey-ho if it's not broke don't fix it.

谢谢大家的帮助。虽然我无法得到任何一个工作答案但它给了我一些想法,我已经完成了这份工作!我最后还是以一种啰嗦的方式来解决这个问题,但如果它没有破坏就嘿嘿,不要修理它。

if ($row[$req_type]=='House'){
    $sel_req_type1='selected';
}
else if ($row[$req_type]=='Bugalow'){
    $sel_req_type2='selected';
}

etc. etc. etc.

等等

And in the table:

并在表中:

<option $sel_req_type1>House</option>
<option $sel_req_type2>Bulgalow</option>

etc. etc. etc.

等等

I still have other issues to overcome i.e. htmlentities for the text fields and quoting the array elements (ie $row['req_type'] instead of $row[req_type]. But I'll ask that on another question. Thanks again

我还有其他问题需要克服,即文本字段的htmlentities和引用数组元素(即$ row ['req_type']而不是$ row [req_type]。但我会问另一个问题。再次感谢

#7


-1  

Here is another way of going about it.

这是另一种方法。

<?php
$query = "SELECT * FROM ".$prefix."_users WHERE userid='$userid'";
$result = mysql_query($query); ?>
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
<select name="venue">
<?php
    while($row = mysql_fetch_array($result)) {
        print '<option value="'.$option.'"';
        if($row['req_type'] == $option) {
            print 'selected';
        }
        print '>'.$option.'</option>';
    } 
?>
</select>

#1


5  

using your current code:

使用您当前的代码:

<?php
  $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

  foreach($options as $option) {
    if ($option == $row['req_type']) {
      print '<option selected="selected">'.$option.'</option>'."\n";
    } else {
      print '<option>'.$option.'</option>'."\n";
    }
  }
?>

assuming $row['req_type'] is one of the values in $options. i strongly suggest quoting your array elements (ie $row['req_type'] instead of $row[req_type]. the latter method generates errors under error_reporting(E_ALL)

假设$ row ['req_type']是$ options中的值之一。我强烈建议引用你的数组元素(即$ row ['req_type']而不是$ row [req_type]。后一种方法在error_reporting(E_ALL)下生成错误

you also might want to look at resources such as phpbuilder.com. some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).

您也可以查看phpbuilder.com等资源。有些文章已经过时,但会为您提供有关如何更好地构建代码的一些基础知识。 (例如,将HTML与PHP代码分开,可以帮助您更好地理解这种情况)。

edit: as per the comments, any information displayed should be escaped properly (see htmlentities() for example).

编辑:根据评论,显示的任何信息都应该正确转义(例如,参见htmlentities())。

#2


1  

Nigel,

See the answer with the check mark next to it. It go me start in solving my problem. First I select my data from the table, then I select the data i want display in my dropdown menu. If the data from the primary table matches the data from the dropdown table selected is echoed.

请在旁边用复选标记查看答案。它让我开始解决我的问题。首先,我从表中选择我的数据,然后在我的下拉菜单中选择我想要显示的数据。如果主表中的数据与所选下拉表中的数据匹配,则回显。

$query9 = "SELECT *
       FROM vehicles
       WHERE VID = '".$VID."'
       ";

$result9=mysql_query($query9);
while($row9 = mysql_fetch_array($result9)){
    $vdate=$row9['DateBid'];
    $vmodelid=$row9['ModelID'];
    $vMileage=$row9['Mileage'];
    $vHighBid=$row9['HighBid'];
    $vPurchased=$row9['Purchased'];
    $vDamage=$row9['Damage'];
    $vNotes=$row9['Notes'];
    $vKBBH=$row9['KBBH'];
    $vKBBM=$row9['KBBM'];
    $vKBBL=$row9['KBBL'];
    $vKBBR=$row9['KBBR'];
    $vYID=$row9['YID'];
    $vMID=$row9['MID'];
    $vModelID=$row9['ModelID'];
    $vELID=$row9['ELID'];
    $vECID=$row9['ECID'];
    $vEFID=$row9['EFID'];
    $vColorID=$row9['ColorID'];
    $vRID=$row9['RID'];
    $vFID=$row9['FID'];
    $vDID=$row9['DID'];
    $vTID=$row9['TID'];
}

$query1 = "SELECT * FROM year ORDER BY Year ASC";
$result1=mysql_query($query1);
echo "<select  name='Year'>";
while($row1 = mysql_fetch_array($result1)){
    echo "<option value = '{$row1['YID']}'";
    if ($vYID == $row1['YID'])
        echo "selected = 'selected'";
    echo ">{$row1['Year']}</option>";
}
echo "</select>";

#3


0  

May not be efficient, but it's simple & gets the job done.

可能效率不高,但很简单并完成工作。

$dropdown = str_replace("<option value=\"".$row[column]."\">","<option value=\"".$row[column]."\" selected>",$dropdown);

#4


0  

Thanks Owen. Your code seems perfect but gave lots of php errors. I simplified it to this but just get whitespace as options:

谢谢欧文。你的代码看起来很完美但是给了很多php错误。我把它简化为这个但只是得到空白作为选项:

<td>Select from list: <select name=\"req_type\">        

$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

foreach($option as $option) {  
if ($option == $row[req_type]) {    
    <option selected>$option</option>} 
else {    
<option>$option</option>}};
</select></td>

#5


0  

        <?php
            $result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");    
            $row = $db->sql_fetchrow($result);

            // options defined here
            $options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');

       ?>     
            <center><font class="title"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />

            <center> All fields must be filled </center> 
            <form name="EditMyInfoForm" method="POST" action="users.php" enctype="multipart/form-data">           
              <table align="center" border="0" width="720" id="table1" cellpadding="2" bordercolor="#C0C0C0">        
                <tr>                
                  <td align="right">Telephone :</td>                
                  <td>
                    <input type="text" name="telephone" size="27" value="<?php echo htmlentities($row['telephone']); ?>" /> Inc. dialing codes
                  </td>        
                </tr>        
                <tr>                
                  <td align="right">Type of property required :</td>                                          
                  <td>Select from list:
                    <select name="req_type">
                  <?php foreach($options as $option): ?>     
                      <option value="<?php echo $option; ?>" <?php if($row['req_type'] == $option) echo 'selected="selected"'; ?>><?php echo $option; ?></option>                  
                  <?php endforeach; ?>
                     </select>  
                   </td>          
                  </tr>

...

oops.. a little too carried away.

哎呀......有点太过分了。

#6


0  

Thanks everyone for all your help. Although I couldn't get any one answer to work it gave me ideas and I have accomplished the job! I ended up going about it a long-winded way but hey-ho if it's not broke don't fix it.

谢谢大家的帮助。虽然我无法得到任何一个工作答案但它给了我一些想法,我已经完成了这份工作!我最后还是以一种啰嗦的方式来解决这个问题,但如果它没有破坏就嘿嘿,不要修理它。

if ($row[$req_type]=='House'){
    $sel_req_type1='selected';
}
else if ($row[$req_type]=='Bugalow'){
    $sel_req_type2='selected';
}

etc. etc. etc.

等等

And in the table:

并在表中:

<option $sel_req_type1>House</option>
<option $sel_req_type2>Bulgalow</option>

etc. etc. etc.

等等

I still have other issues to overcome i.e. htmlentities for the text fields and quoting the array elements (ie $row['req_type'] instead of $row[req_type]. But I'll ask that on another question. Thanks again

我还有其他问题需要克服,即文本字段的htmlentities和引用数组元素(即$ row ['req_type']而不是$ row [req_type]。但我会问另一个问题。再次感谢

#7


-1  

Here is another way of going about it.

这是另一种方法。

<?php
$query = "SELECT * FROM ".$prefix."_users WHERE userid='$userid'";
$result = mysql_query($query); ?>
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
<select name="venue">
<?php
    while($row = mysql_fetch_array($result)) {
        print '<option value="'.$option.'"';
        if($row['req_type'] == $option) {
            print 'selected';
        }
        print '>'.$option.'</option>';
    } 
?>
</select>