我已填充sql
php
结果中的下拉列表,现在我尝试将所选值设置为同一页面中的php
变量,但它无法正常工作。你能帮我吗。以下是代码。
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<option value='" . $row['col_of_fac'] . "'>" . $row['col_of_fac'] . "
</option>";
}
echo "</select>";
$varsel = $_POST['list'];
echo "hai";
echo $varsel;
?>
$varsel = $_POST['list'];
无效。
答案 0 :(得分:0)
你应该
1-使用表格
2-使用方法“POST”将变量发送到同一个文件php
<?php
// display the errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
// when the form submitted
if(!empty($_POST['list'])){
echo $_POST['list'];
}
?>
<?php
// connection test
$conn=mysqli_connect("localhost","user","pass","db"); //replace the (user, pass, db) with your parameters
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//if your connection succeded
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
?>
<form method="post" action="<?= $_SERVER['PHP_SELF']; ?>">
<select name="list">
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)): ?>
<option value="<?= $row['col_of_fac']; ?>"><?= $row['col_of_fac']; ?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="valider">
</form>
如果您想打印所选的值而不是没有表单
然后你必须使用jquery
<?php
// display the errors
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
<?php
// when the form submitted
if(!empty($_POST['list'])){
echo $_POST['list'];
}
?>
<?php
// connection test
$conn=mysqli_connect("localhost","user","pass","db"); //replace the (user, pass, db) with your parameters
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
//if your connection succeded
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
?>
<select name="list">
<?php while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)): ?>
<option value="<?= $row['col_of_fac']; ?>"><?= $row['col_of_fac']; ?></option>
<?php endwhile; ?>
</select>
<p id="value-selected"></p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function(){
$("select[name=list]").on("change", function () {
var valueSelected = $(this).val();
$("#value-selected").html(valueSelected);
});
});
</script>
答案 1 :(得分:0)
$ varsel = $ _POST ['list'];不管用。 :只有在通过post方法提交表单时才会起作用,
(打印当前代码选择框,您无需提交表单即可获取帖子) 逻辑应该是这样的 在表格选择框中使用您的以下代码和用户选择,然后单击提交:
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy" ;
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
echo "<option value='" . $row['col_of_fac'] . "'>" . $row['col_of_fac'] . "
</option>";
}
echo "</select>";
?>
在下面提交的表单应该执行后,在网络控制台中,在页眉中,您可以看到所需的数据是否已传输到请求的页面