简体   繁体   中英

Populate multi-select with php while loop from db

The following worked on a local environment. Now that it's pushed live everything but these seems to work. Displays completely empty select boxes now no checks or blank labels just empty space in the "select options" drop down. select display

<?php
  $selected = array();
  $selected = explode(",",$fill['markets']);

  $condb = mysql_query("SELECT * FROM `countries`");
  $count = mysql_num_rows($condb);
  $countries = array();
  $str;

  while ($countries = mysql_fetch_array($condb))
  {
    $str = "option{$countries['id']}";
    echo "<option value='{$str}' ";
    if(in_array($str,$selected)) {
      echo "selected>";
      echo $countries['country'];
      echo "</option>";
    } else {
      echo ">";
      echo $countries['country'];
      echo "</option>";
    }
  }      
  ?>

You should use while loop instead. You can declare $i outside the loop if you need it, Try the following code:

  $condb = mysql_query("SELECT * FROM `countries`");

  $i = 0;
   while($countries = mysql_fetch_array($condb)) {
    $str = 'option' . $i;
    echo "<option value='{$str}' ";
    if(in_array($str,$selected)) {
      echo "selected>";
      echo $countries['country'];
      echo "</option>";
    } else {
      echo ">";
      echo $countries['country'];
      echo "</option>";
    }
 $i++;
  }
  ?>
</select>

Note:

mysql_* is deprecated as of . So instead use mysqli_* or PDO .
Why shouldn't I use mysql_* functions in PHP?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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