在表单中显示所选值

时间:2014-04-04 11:40:42

标签: php sql forms mysqli

如何将选定的值放在变量中并以另一种形式显示?

enter image description here

代码:

$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno()){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"Select name from pools");
echo "<form action='' method='POST' ><select name='mypool'>";

$default_name = "foo_bar"; 
while($row = mysqli_fetch_array($result)){
  $opt_name = $row['name'];
  $str_selected = "";
  if($opt_name == $default_name){
      $str_selected = "selected";
  }
  echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
}
echo "<input type='submit' name='submit' value='submit'/>";
echo "</select></form>";
mysqli_close($con);




if (isset($_Post['submit']))
{

echo $_POST['mypool'];

}

3 个答案:

答案 0 :(得分:0)

使用此:

$default_name = "foo_bar"; 
while($row = mysqli_fetch_array($result)){
  $opt_name = $row['name'];
  if($opt_name == $default_name){
     echo "<option value='".$opt_name."' selected='selected'>" . $opt_name. "</option>"; 
  } else {
     echo "<option value='".$opt_name."'>" . $opt_name. "</option>";
  }
}

答案 1 :(得分:0)

简单,只需使用表单标签并发布,

<?php
$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno()){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"Select name from pools");
echo "<form action='ANOTHERPAGEURL' method='POST' ><select name='mypool'>";

$default_name = "foo_bar"; 
while($row = mysqli_fetch_array($result)){
  $opt_name = $row['name'];
  $str_selected = "";
  if($opt_name == $default_name){
      $str_selected = "selected";
  }
  echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
}
echo "</select></form>";
mysqli_close($con);
?>

在另一页中使用它,

<?php
echo $_POST['mypool'];
?>

希望这有效

答案 2 :(得分:0)

你必须创建一个<form>并发布它。

试试这段代码:

if(isset($_POST['mypool']))
   echo "Value is: " . $_POST['mypool'];

echo "<form method='POST' action='#'>";
echo "<select name='mypool'>";

$default_name = "foo_bar"; 
while($row = mysqli_fetch_array($result)){
  $opt_name = $row['name'];
  $str_selected = "";
  if($opt_name == $default_name){
      $str_selected = "selected";
  }
  echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
}
echo "</select>";

echo "<input type='submit' name='send' />";
echo "</form>";

如果您想在另一个页面上处理帖子,只需将action='#'替换为action='yourPage.php'并将此代码移到那里:

if(isset($_POST['mypool']))
       echo "Value is: " . $_POST['mypool'];