使用PHP选择基于会话变量的下拉选项

时间:2013-04-01 16:29:35

标签: php select drop-down-menu

我正在使用PHP通过Javascript追加填充HTML下拉菜单的选项。它到目前为止工作,我使用条件语句只显示该团队ID的值,如果设置了会话变量。问题是我需要显示所有下拉选项(如PHP中的else / while语句),即使设置了会话变量,这样人们仍然可以选择手动选择另一个ID,但如果设置了会话,则自动选择值会话变量设置为....否则只显示选择默认选项(1)的选项,就像在我的else语句中一样。关于我应该怎么做的任何建议?谢谢!

HTML

<td class="label_container">Team ID#</td>
            <td class="input_container">
            <select id="prepping_team" name="prepping_team"></select>
            </td>

JS

//Populate Team IDs
function get_prepping_team() {
$.ajax({
    url: './php/getprepping_team.php',
    success: function(data) {
        $('#prepping_team').append(data);
    }
});
};

PHP

//Grab Session (if set)
session_start();
$_SESSION['prepping_team'];

$prep_team = $_POST['prepping_team'];

header("Cache-Control: no-cache, must-revalidate");
header('Access-Control-Allow-Origin: *');
header('Content-type: multipart/form-data');

$logAuditFile = "../log/prepform.log";
$logModule = "getprepping_team.php";
include '/mnt/library/auditlog.php';

require("/mnt/library/configdb.php");        
include '/mnt/library/accessdb.php';

//Parse and store the db ini file, this will return an associative array
db_config_cables_test();
db_connect();

$sql = mysql_query("SELECT pt_id FROM preppingteam;");
//IF SESISON VARIALBE IS SET
if(isset($_SESSION['prepping_team'])) {
    print "<option value=\"".$_SESSION['prepping_team']."\">".$_SESSION['prepping_team']."</option>";
    //print "<option value=\"".$_SESSION['prepping_team']."\">".$_SESSION['prepping_team']."</option>";
//OTHERWISE LOAD TEAM IDs
} else {
    while ($data = mysql_fetch_assoc($sql)) {
        print "<option value=\"".$data['pt_id']."\">".$data['pt_id']."</option>";
    }
}

1 个答案:

答案 0 :(得分:1)

代码的最后一部分没有做你想要的。所以像这样纠正它

<强>更新

while ($data = mysql_fetch_assoc($sql)) {
   if(isset($_SESSION['prepping_team']) && $_SESSION['prepping_team'] == $data['pt_id'])
    {
    print "<option selected = 'selected'  value=\"".$_SESSION['prepping_team']."\">".$_SESSION['prepping_team']."</option>";    
    }
   else
    print "<option value=\"".$data['pt_id']."\">".$data['pt_id']."</option>";
}