在表格中选择一个介于 2 个逗号之间的单词 PHP 不起作用


select a word in table between 2 commas php is not working

首先我的 mysql 表土地是:NL,BE,DE,AF我想先爆炸而不是我想要的爆炸词,如果它等于选项值,然后选择该选项

$resultxx = mysql_query("SELECT * FROM page where page_id = '$page_id'") or   die(mysql_error());
$number=mysql_num_rows($resultxx); 
    while($land = mysql_fetch_array($resultxx)){ 
     $exp = explode(',', $land['land']);
     }

$count = 0;
//Check if space exists in substrings
foreach ($exp as $code) {
  if (strpos(trim($code), ' ') == false) { //strpos better for checking existance
      $count++;
      $land = constant(COUNTRY_.$code);
        ?>
<option selected value="<?php echo $code; ?>"><?php echo $land; ?></option>
     <?php
  }}
 ?>
 </select>

试试这个

<select class="multi" multiple="multiple" id="my-select" name="my-select[]">
  <?php
$resultxx = mysql_query("SELECT * FROM page where page_id = 1") or       
 die(mysql_error());
 $number=mysql_num_rows($resultxx); 
    while($land = mysql_fetch_array($resultxx)){
     $exp = explode(',', $land['land']);
?>
<option <?php if(in_array("AF",$exp)) echo "selected='selected'"; ?> value="AF"><?php echo COUNTRY_AF; ?></option>
<option <?php if(in_array("NL",$exp)) echo "selected='selected'"; ?> value="NL"><?php echo COUNTRY_NL; ?></option>

<option <?php if(in_array("DE",$exp)) echo "selected='selected'"; ?> value="DE"><?php echo COUNTRY_DE; ?></option>
</select>
<?php }

如果$land['land']是像'AF,BE,NL,DE'这样的字符串,那么你得到数组。您可以使用如下foreach遍历数组:

foreach($exp as $val){
  if ($val == 'AF') {/*do something*/}
  if ($val == 'AR') {/*do something*/}
}

也许这可以做到?只需确保在数组中定义所有国家/地区$countries即可。你怎么做并不重要,但由于我不知道你从哪里得到国家列表,所以我在顶部定义了它。

<select class="multi" multiple="multiple" id="my-select" name="my-select[]">
    <?php
    $countries = array('AF', 'NL', 'DE', 'BE');
    $resultxx = mysql_query("SELECT * FROM page where page_id = 1") or       
    die(mysql_error());
    $number=mysql_num_rows($resultxx);
    while($land = mysql_fetch_array($resultxx)){
        $exp = explode(',', $land['land']);
        for($i = 0; $i <= count($countries); $i++){ 
            ?>
            <option<?php echo in_array($countries[$i], $exp) ? ' selected' : '' ?> value="<? print $countries[$i]; ?>">
                <?php echo constant('COUNTRY_'.$countries[$i]); ?>
            </option>
            <?php
        }
    }
    ?>
</select>