1

我正在尝试将所有行作为选择框选项返回,但它只返回第一行

while($parent_cat = mysql_fetch_array( $result )) 

{
   return '<option value="'.$parent_cat['categoryid'].'">'.$parent_cat['title'].'</option>';
}

我怎样才能返回所有行?

4

2 回答 2

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>
于 2013-03-22T19:41:35.633 回答
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();
        ?>
于 2016-02-25T03:49:59.353 回答