简体   繁体   English

从数据库和数组加载选择框值

[英]Loading select box values from DB and array

I have a code that will first load all the values into an array. 我有一个代码,它将首先将所有值加载到数组中。 The values will be then given to select box. 然后将这些值提供给选择框。 There will be totally 5 select boxes and it will load the same data. 总共有5个选择框,它将加载相同的数据。 I have tried my level best. 我已经尽力了。 And here is the code 这是代码

    <?php
    $resultSet = array();
    while($result = mysql_fetch_array($result_book_query))
    {
    $resultSet['Book_Code'][] = $result['Book_Code'];
    $resultSet['Book_Name'][] = $result['Book_Name'];
    }
    ?>

    <?php for($i=1; $i<=5; $i++) { ?>
    <select name="book_code_<?php echo $i; ?>" id="book_code">
    <option value=""></option>
    <option value="<?php  echo $resultSet['Book_Code'];?>"><?php  echo $resultSet['Book_Name'] ;?></option>
    </select>
    <?php } ?>

What I'm trying to do is. 我想做的是。

Show 5 select box with the same values (ie the values wil be first loaded from DB and stored in array) and then load it inside the select box. 显示5个具有相同值的选择框(即,这些值将首先从DB加载并存储在数组中),然后在选择框内加载。

Thanks, Kimz 谢谢,金兹

This is not very handy way to operate with database results, seems as copy-pasted from an example with little understanding. 这不是处理数据库结果的便捷方法,似乎是从一个几乎没有理解的示例中复制粘贴的。 Try it this way: 尝试这种方式:

<?php
$resultSet = array();
while($result = mysql_fetch_array($result_book_query))
{
    $resultSet[] = $result; //the code you had here is maybe working, but very unhandy
}
?>

<?php for($i=1; $i<=5; $i++) { ?>
  <select name="book_code_<?php echo $i; ?>" id="book_code">
  <option value=""></option>
  <?php foreach ($resultSet as $result) { //THIS is the important thing you missed
?>
    <option value="<?php  echo htmlspecialchars($result['Book_Code']);?>"><?php  echo htmlspecialchars($result['Book_Name']) ;?></option>
  <? } ?>
</select>
<?php } ?>

Also, ALWAYS escape variables written to HTML using htmlspecialchars. 另外,始终使用htmlspecialchars来转义写入HTML的变量。

Alright, so as per the comment below, you can do: 好的,按照下面的评论,您可以执行以下操作:

<?php for($i=1; $i<=5; $i++) { ?>
<select name="book_code_<?php echo $i; ?>" id="book_code">
<option value=""></option>
<?php foreach($resultSet['Book_Code'] as $k=>$v){
   echo "<option value=".$v.">".$resultSet['Book_Name'][$k]."</option>";
}
?>
</select>
<?php } ?>
<?php
$resultSet = array();
while($result = mysql_fetch_array($result_book_query))
{
$resultSet[] = array(
                    'Book_Code' => $result['Book_Code'],
                    'Book_Name' => $result['Book_Name']
                    );
}
?>

<?php for($i=1; $i<=5; $i++): ?>
<select name="book_code_<?php echo $i; ?>" id="book_code">
<option value=""></option>
<?php foreach($resultSet as res):?>
    <option value="<?php  echo $res['Book_Code'];?>"><?php  echo $res['Book_Name'] ;?></option>
<?php endforeach;?>

</select>
<?php endfor;} ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM