我试图将所有行作为选择框返回选项,但它只返回第一行
while($parent_cat = mysql_fetch_array( $result ))
{
return '<option value="'.$parent_cat['categoryid'].'">'.$parent_cat['title'].'</option>';
}
如何退回所有行?
答案 0 :(得分:2)
您可以通过传递一些属性作为参数并根据需要构建动态下拉来扩展以下功能。
function showDropDown() {
$html = '<select>';
$i = 0;
while (your loop condition) {
$html .= '<option value="">Hello World</option>';
$i++;
}
$html .= '</select>';
//in case your loop fails return empty instead of drop down without options.
return $i > 0 ? $html : '';
}
echo showDropDown();
我使用上述功能的方式是:
function buildDropDown(array $array, $attributes = array()) {
if (! empty($array)) {
$html = '<select ';
foreach($attributes as $attr => $val) {
$html .= $attr . '="' . $val . '" ';
}
foreach($array as $key => $value) {
$html .= '<option value="'.$key.'">'.$value.'</option>';
}
$html .= '</select>';
return $html;
}
return '';
}
$testArr = array(1 => 'A', 2 => 'B', 3 => 'C');
$attrs = array(
'id' => 'hello',
'name' => 'hello',
'style' => 'background-color: blue'
)
echo buildDropDown($testArr, $attrs);
上面生成:
<select id="hello" name="hello" style="background-color:blue">
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
答案 1 :(得分:0)
我设法以这种方式解决了这个问题。
function openDB()
{
global $conn, $username,$host,$password,$db;
$host = "localhost";
$username ="username";
$password= "password";
$db = "databasename";
$conn = mysql_connect($host, $username,$password) or die(mysql_error());
mysql_select_db($db,$conn) or die(mysql_error());
}
function closeDB()
{
global $conn;
mysql_close($conn);
}
openDB();
$query3 = "select * from table_name";
$result2 = mysql_query($query3,$conn)
or die ("Error in query: $query.". mysql_error());
// if a result
if(mysql_num_rows($result) > 0)
{
//turn it into an object
$row = mysql_fetch_object($result);
if(mysql_num_rows($result2) > 0)
{
//turn it into an object
$row2 = mysql_fetch_object($result2);
?>
<?
//creates a options box for the list of items in the dropdownmenu
echo"<select>";
while($row2=mysql_fetch_array($result2))
{
echo "<option>".$row2['feild_title']."</option>";
}
echo"</select>";
closeDB();
?>