我的代码需要一些帮助。我将数据存储在$_SESSION
数组中时正在从数据库中获取数据。现在,我想在列表框中插入数据,但是在列表框中插入数据时遇到了问题。
当我尝试这样做时:
<select id="gender" name="gender" class="form-control" value='<?php echo htmlspecialchars($_SESSION["gender"]); ?>'>
<option value="unknown"></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
它不会在列表框中插入数据,因为列表框显示列表框中没有插入数据。
这是完整的代码:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
//print_r($_SESSION);
?>
<select id="gender" name="gender" class="form-control" value='<?php echo htmlspecialchars($_SESSION["gender"]); ?>'>
<option value="unknown"></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
$_SESSION
数组显示的内容如下:
Array
(
[loggedin] => 1
[id] => 1
[username] => myusername
[firstname] => Robert
[lastname] => Jones
[email] => xxx.xxxxxxx@xxxxx.com
[gender] => Male
[states] => United Kingdom
)
能否请您举一个示例,说明如何使用我从$_SESSION
数组中提取数据的php echo将数据插入到列表框中?
谢谢。
答案 0 :(得分:2)
我将通过PHP生成此选择
$html = '<select id="gender" name="gender" class="form-control">';
$values = array('unknown', 'Male', 'Female');
foreach($values as $v){
$selected = '';
if($v == 'unknown'){
$title = '';
}else{
$title = $v;
}
if($v == $_SESSION["gender"]){
$selected = "selected";
}
$html .= "<option $selected value='$v'>$title</option>";
}
$html .= "</select>";
echo $html;