我试图返回所有行作为一个选择框选项,但它是只返回第一行返回而循环中的所有行的下拉选择框中选择
while($parent_cat = mysql_fetch_array($result))
{
return '<option value="'.$parent_cat['categoryid'].'">'.$parent_cat['title'].'</option>';
}
我怎样才能返回所有的行?
我试图返回所有行作为一个选择框选项,但它是只返回第一行返回而循环中的所有行的下拉选择框中选择
while($parent_cat = mysql_fetch_array($result))
{
return '<option value="'.$parent_cat['categoryid'].'">'.$parent_cat['title'].'</option>';
}
我怎样才能返回所有的行?
您可以通过传递一些属性作为参数并根据需要构建动态下拉菜单来扩展以下功能。
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>
它只返回最后一行。我有这个函数,我必须调用这个函数到另一个代码,它只允许传递返回值而不是回声。回声渲染出空间 – 2013-03-22 19:48:12
等待我认为它会工作..只需给我几分钟的时间来测试 – 2013-03-22 19:49:59
我设法这种方式拉这一关。
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();
?>
[**请不要在新代码**中使用'mysql_ *'函数](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。看到[**红框**](http://j.mp/Te9zIL)?学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。 – Kermit 2013-03-22 19:39:15
感谢它,但最终mysql函数将取代CMS自己的功能,所以我会在那种情况下没事的吧? – 2013-03-22 19:43:03