0

Hi I have a piece of php code which takes php variables from a database and then populates A drop down box. This works fine but once the page updates it doesn't display the selected value and instead just displays the original list again.

I have played around with some different ideas of using isset to displays the selected value, but then it just displays that value and nothing else.

I have attached the original code where it works but always only shows the original list of values from the database.

If any body could provide a solution or even a nudge in the right direction then it would be much appreciated.

Thanks

if (isset($select) && $select != "location") {
    $select = $_POST['location'];
}
?>

<select name="location">
<?php
// Get records from database (table "name_list").
$list = mysql_query("select DISTINCT region_name from masterip_details WHERE country_code='GB' AND TRIM(IFNULL(region_name,'')) <> '' order by region_name asc");

// Show records by while loop.
while ($row_list = mysql_fetch_assoc($list)) {
    $location = $_POST['location']; ?>
    <option value="<?php echo $row_list['region_name']; ?>"
    <?php if  $row_list['region_name'] == $select) {
        echo "selected";
    } ?>><?php echo $row_list['region_name']; ?></option>        
<?php } ?>
4

4 回答 4

1

您没有正确检查选择值。

改变这个:

if (isset($select) && $select != "location") {
    $select = $_POST['location'];
}

if (isset($_POST['location']) && $_POST['location'] != "location") {
    $select = $_POST['location'];
}
于 2013-07-18T10:02:39.663 回答
1

您确定您发送该表格并附有邮寄请求吗?

你的代码不可读最好做这样的事情:

<?php

    //database request don't belong in the presentation layer
    $list=mysql_query("select DISTINCT region_name from masterip_details WHERE country_code='GB' AND TRIM(IFNULL(region_name,'')) <> '' order by region_name asc");
    $location = "";
    $isSelect = "";
    if(isset($_POST['location'])){
        $location = $_POST['location']; 
    }
    while($row_list=mysql_fetch_assoc($list)){
        if($row_list['region_name'] == $location ){ 
            $isSelect = "selected"; 
         } 
         echo '<option value="'.$row_list['region_name'].'" '.$isSelect.'  >'. $row_list['region_name'].'</option>';

    }
?>
于 2013-07-18T09:57:35.070 回答
0

问题出在第一行 - 实际上系统永远不会执行第二行来分配$select,因为$select从未设置:

if(isset($_POST['select']) && $select!="location") { $select=$_POST['location']; } ?>
于 2013-07-18T10:04:25.033 回答
0

创建<option>标签时,您可以使用以下内容:

<?php if ($row_list['region_name'] == $select) { echo "selected='true'"; } ?>

您可能还想检查条件$row_list['region_name'] == $select是否正在返回true。您可以分别尝试echo他们的结果:

echo ($row_list['region_name'] == $select)

或类似的东西会显示你是否得到true

于 2013-07-18T09:59:48.920 回答