简体   繁体   English

HTML选择不显示所有选项

[英]HTML Select Not Showing All Options

I have a form with a dynamic select option inside which is taking its options from a database through PHP. 我有一个带有动态select选项的表单,该表单通过PHP从数据库中获取其选项。 The main problem is that although it is working, it is not showing the first record from database. 主要问题是,尽管它正在运行,但未显示数据库中的第一条记录。 This is the code: 这是代码:

<select name="elevi" >
    <?
    $sql="Select * from elevi";
    $query=mysql_query($sql)or die(mysql_error());
    $result=mysql_fetch_array($query);
    while($result=mysql_fetch_array($query)){
        echo'<option value="'.$result['id_elev'].'">'.$result['nume']."".$result['prenume'].'</option>';
    }
    ?>
</select>

Remove the first $result=mysql_fetch_array($query); 删除第一个$result=mysql_fetch_array($query);

This line basically throws away the first record. 该行基本上会丢弃第一条记录。

In the while loop, you do 2 things, assign $result with the result of mysql_fetch_array(), and check if that result is null or not. 在while循环中,您要做2件事,为$ result分配mysql_fetch_array()的结果,然后检查该结果是否为null。

mysql_fetch_array() moves its internal data pointer forward by one each time it is called, until there are no more options and it returns false. 每次调用mysql_fetch_array()时,其内部数据指针都会向前移动一个,直到没有更多选项,并且返回false为止。 This is why you can use the while loop. 这就是为什么可以使用while循环的原因。

So if you remove you first $result=mysql_fetch_array($query) call, you'll be fine. 因此,如果您先删除了$result=mysql_fetch_array($query)调用,就可以了。

You need to fetch one row at a time 您需要一次获取一行

<select name="elevi" >
    <?php
        $sql="Select * from elevi";
        $query=mysql_query($sql)or die(mysql_error());
     while($result=mysql_fetch_row($query)){
     echo'<option value="'.$result['id_elev'].'">'.$result['nume']." ".$result['prenume'].'</option>';}?>
    </select>

Or in case of bulk data, fetch the array and then loop through the array (the results are however fetched with one call making the code more efficient) 或者在批量数据的情况下,获取数组,然后遍历数组(但是,通过一次调用获取结果,使代码更有效)

you are using $result=mysql_fetch_array($query); 您正在使用$ result = mysql_fetch_array($ query); twice, it should be used once, for example, 两次,应该使用一次,例如,

<select name="elevi" >
<?php
    $sql="Select * from elevi";
    $query=mysql_query($sql)or die(mysql_error());
 while($result=mysql_fetch_row($query)){
 echo'<option value="'.$result['id_elev'].'">'.$result['nume']." ".$result['prenume'].'</option>';}?>
</select>

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

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