我需要sql数据库填充表单输入的值.我的代码适用于所有文本和textarea输入,但我无法弄清楚如何将数据库值分配给下拉列表,例如.'房产类型'如下.它围绕着"选择选项"来表示数据库中保存的值.
这是我的代码:
$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>
....
Run Code Online (Sandbox Code Playgroud)
使用您当前的代码:
<?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";
}
}
?>
Run Code Online (Sandbox Code Playgroud)
假设$row['req_type']是其中一个值$options.我强烈建议引用你的数组元素(即$row['req_type']代替$row[req_type].)后一种方法会产生错误error_reporting(E_ALL)
您也可以查看phpbuilder.com等资源.有些文章已经过时,但会为您提供一些有关如何更好地构建代码的基础知识.(例如,将HTML与PHP代码分开,可以帮助您更好地了解此问题).
编辑:根据评论,显示的任何信息都应正确转义(htmlentities()例如参见).