0

Quick question. So what I need to do is to populate my html droplist with rows from my table. I am able to do this for one html droplist down but the moment I do this with another html droplist, it becomes a problem. you cant use mysql_fetch_array twice. any suggestions?

Below is the sample code which I referenced to do this.

    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
  • Write your full code here. contains both mysql_fetch_array – Maha Dev Oct 09 '15 at 14:12
  • *you cant use mysql_fetch_array twice.* ... ummm? Though, really, you shouldn't use it even once : http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001 Oct 09 '15 at 14:20

3 Answers3

0

Option 1: Use below code. Please read this 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() moves the internal row pointer of the MySQL result associated with the specified result identifier to point to the specified row number.

Option 2: You can store mysql_fetch_array($query) in one array and re-use it.

$sample_array = mysql_fetch_array($query);
while($row = $sample_array){
   // Your code..
}
while($row = $sample_array){
   // Your code..
}
RNK
  • 5,582
  • 11
  • 65
  • 133
0

Simple solution from my side, write a method that will take two arrays and populate Dropdown.

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>';
}
Jitendra Kumar. Balla
  • 1,173
  • 1
  • 9
  • 15
0

Do not use deprecated functions, try MySQLi or PDO. If you need call the return elements from the database, just create an array to store it and use foreach many time as you need.

$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>';
rray
  • 2,518
  • 1
  • 28
  • 38