您好,我有一个下拉菜单,它在选择时执行 Ajax/JavaScript 以将所选值放入数据库中。我希望下次打开带有菜单的页面时,下拉菜单选项被选中从数据库值。这样,用户将知道在数据库中选择了什么。
这是我的下拉菜单的代码:
<?php echo "<select name='status' id='$id' idc='$idc'>" ?>
<option value="">Option:</option>
<option value="val1">Val1</option>
<option value="Val2">Val2</option>
</select>
从菜单中将信息存储在数据库中的功能是:
<script>
$(document).ready(function(e) {
$('select[name=status]').change(function(){
selectstatus = $("select[name=status]").val();
var id = $(this).attr('id');
var idc = $(this).attr('idc');
$.ajax({
type: "POST",
url: "selectbackend.php",
data: {"selectstatus": selectstatus, "id": id, "idc": idc
},
})
.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
这是与数据库的连接,用于存储下拉菜单中的信息:
<?php
$selectstatus = $_POST['selectstatus'];
$id = $_POST['id'];
$idc = $_POST['idc'];
$host = "localhost";
$user = "user";
$password = "pass";
$dbname = "test";
$cxn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}
$query = " UPDATE subscriptions
SET status = '$selectstatus'
WHERE user_id='$idc' AND curso_id='$id'";
$result = mysqli_query($cxn, $query) or die ("could not query database 1");
?>