doujing2497 2011-12-02 02:29
浏览 28
已采纳

用于存储列表项目的PHP变量在页面上多次出现?

Hi All: I am new to creating arrays and am trying to create a variable to hold a list of items and print it multiple times on a page. Below is the PHP that I've attempted and below that is the HTML which shows the same SELECT list multiple times on the page. It is only listing the first item in the SELECT list. Other tweaks have resulted in the SELECT list having the complete list of items from the database, but any other calls to this variable elsewhere on the page fails.

What can I do to get a variable to hold this SELECT list so that I can print it multiple times on the page?

    <?php
    $catresult = mysql_query("SELECT * FROM Classes WHERE FK_UserID=$_SESSION[user_id] ORDER BY ClassName");
    $dataset = array();
    while($row = mysql_fetch_array($catresult)) {
            $dataset = '<option value="' . $row['ClassID'] . '">' . $row['ClassName'] . '</option>';
        }   
    ?>

    <!-- HTML below -->

    Paragraph 1 content...
    <select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>

    Paragraph 2 content...
    <select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>

    Paragraph 3 content...
    <select name="FK_ClassID" /><option value="">Class</option><?php echo $dataset; ?></select>
  • 写回答

3条回答 默认 最新

  • down101102 2011-12-02 02:35
    关注

    Just to clarify what others have already pointed out:

    What you are doing does not require an array. What you want is for $dataset to contain one long string with all the options. So, instead of $dataset = array(); use $dataset = '';.

    In addition, the = sign overwrites whatever was in your variable before that. You don't want that. You want to concatenate (add on) the new string on the old one. For that you'll use .=.

    So, to tie it all together:

    <?php
       $catresult = mysql_query("SELECT * FROM Classes WHERE FK_UserID=$_SESSION[user_id] ORDER BY ClassName");
    
       $dataset = '';
    
       while( $row = mysql_fetch_array($catresult) )
       {
           $dataset .= '<option value="' . $row['ClassID'] . '">' . $row['ClassName'] . '</option>';
       }   
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答