我从数据库中获取一组值以显示在下拉列表中。一旦用户从下拉列表中选择了一个项目,就应该将所选项目分配给一个SESSION变量。我试过这个,但它没有用。请你帮我解决一下。
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
所以我需要将$ row [Form_ID]和$ row [Form_Name]中的这些值存储在名为$ _SESSION ['Form_ID']和$ _SESSION ['Form_Name']的2个会话变量中;有人可以解释我如何将所选项目的值分配给这两个会话变量。
答案 0 :(得分:1)
所选的option
元素必须具有selected
属性。
你应该尝试这样的事情:
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; ">
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result))
{
echo "<option value='{$row['Form_ID']}'";
if($row['Form_ID'] == $_SESSION['Form_ID'])
echo " selected";
echo ">{$row['Form_Name']}</option>";
}
?>
</select>
<强>更新强>
您可以在表单提交
后将其存储在$_SESSION
中
<?php
session_start(); // dont forget it!
if(isset($_POST['submit']))
{
$_SESSION['Form_ID'] = $_POST['Form_ID'];
$_SESSION['Form_Name'] = $_POST['Form_Name'];
}
?>
答案 1 :(得分:0)
试试这个
<form name="my_name" method="POST" action="">
<select name="FormNameSelecting" id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "> //don't forget put name at select
<option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_assoc($result)){ //prefer using assoc that array
echo "<option value='" . $row['Form_ID'] . ":::" . $row['Form_Name'] . "'>" . $row['Form_Name'] . "</option>";
}
?>
</select>
<input type="submit" name="go" value="go"/>
</form>
<?php
if(isset($_POST['go'])){
$store_sesi = explode(":::",$_POST['FormNameSelecting']);
$_SESSION['ID'] = $store[0];
$_SESSION['Name'] = $store[1];
}
?>
希望此代码可以帮助您
答案 2 :(得分:0)
试试这个: 在你的页面中添加这个并再创建一个页面“showValues.php”(这是你要创建和使用会话变量的页面)。例如,showValues.php的代码也在下面给出。
<html>
<head>
<script>
function showValue(vals)
{
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var val= xmlhttp.responseText;
document.getElementById("tbl").innerHTML+=val;
}
}
xmlhttp.open("GET","showValues.php?vals="+vals,true);
xmlhttp.send();
}
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
<select id="FormNameSelecting" style="position:absolute; width:300px; top:50px; left:200px; "><option></option>
<?php
$result = mysqli_query($con,"SELECT * FROM Form");
while($row = mysqli_fetch_array($result)){
echo "<option value='$row[Form_ID]'>$row[Form_Name]</option>";
echo
}
?>
</select>
</td>
</tr>
</table>
</body>
</html>
<强> showValues.php 强>
<?php
session_start();
$vals=$_REQUEST['vals'];
$_SESSION['SelectValue']=$vals;
echo $_SESSION['SelectValue'];
?>