2015-10-09 127 views
0

快速问题。所以我需要做的是用我的表中的行填充我的html下拉列表。我可以为一个HTML下拉列表做这件事,但当我用另一个html下拉列表做这件事时,它就成了一个问题。你不能使用mysql_fetch_array两次。有什么建议么?从数据库行提取数据并填充选择标签

以下是我参考的示例代码。

query = mysql_query("YOUR QUERY HERE"); // Run your query 

echo '<select name="DROP DOWN NAME">'; // Open your drop down box 

// Loop through the query results, outputing the options one by one 
while ($row = mysql_fetch_array($query)) { 
    echo '<option value="'.$row['something'].'">'.$row['something'].'</option>'; 
} 

echo '</select>';// Close your drop down box 
+0

在这里写下您的完整代码。包含两个mysql_fetch_array –

+0

*你不能使用mysql_fetch_array两次。* ... ummm?虽然,真的,你不应该使用它甚至一次:http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001

回答

0

选项1: 使用下面的代码。请阅读本document

while($row = mysql_fetch_array($query)){ 
    // Your code.. 
} 

// add this line 
mysql_data_seek($query, 0); 

while($row = mysql_fetch_array($query)){ 
    // Your code.. 
} 

mysql_data_seek()移动与指定结果标识符相关联的MySQL的结果的内部行指针指向指定的行数。

选项2: 可以存储mysql_fetch_array($query)在一个阵列中,并重新使用它。

$sample_array = mysql_fetch_array($query); 
while($row = $sample_array){ 
    // Your code.. 
} 
while($row = $sample_array){ 
    // Your code.. 
} 
+0

非常感谢你:) –

0

从我这边简单的解决方法,写一个方法,将采取两个数组并填充下拉菜单。

function populateDropDown($values,$displayArray, $nameDropdon){ 
echo "<select name='$nameDropdon'>"; // Open your drop down box 

// Loop through the query results, outputing the options one by one 
for($i=0;i<count($values);$i++) 
    echo '<option value="'.$values[$i].'">'.$displayArray[$i].'</option>'; 

echo '</select>'; 
} 
0

不要使用不建议使用的函数,请尝试MySQLi或PDO。如果您需要从数据库中调用返回元素,只需创建一个数组来存储它并根据需要使用多个时间段。

$query = mysql_query("YOUR QUERY HERE") or die(mysql_error()); 

$items = array(); 
while ($row = mysql_fetch_array($query)) { 
    $items[] = $row; 
} 


echo '<select name="DROP DOWN NAME">'; 
foreach($items as $item){ 
    printf('<option value="%d">%s</option>', $item['id'], $item['description']); 
} 
echo '</select>';