提交表单后无法获取变量


Cant fetch variable after submitting the form

变量 $role_id1 未在 $_POST['add sub menu'] 的 $role_id 中获取。 我想将 $role_id1 存储在 $role_id 中并插入到数据库中。如果我单击提交按钮,role_id1正在获取父菜单,但在我单击添加子菜单后,role_id在后端存储 0。但我希望它存储role_id1谷,这是我单击提交后正在获取的。如果可能,建议任何解决方案。

  <?php
 $dbcon = new MySQLi("localhost","root","","menu");
if(isset($_POST['add_main_menu']))
{
$menu_name = $_POST['menu_name'];
$parent_id = 0;
$role_id = $_POST['role_id'];
$menu_link = $_POST['mn_link'];
$sql=$dbcon->query("INSERT INTO menu   VALUES('','$menu_name','$parent_id','$role_id','$menu_link')");
}
  if(isset($_POST['add_sub_menu']))
{
$parent_id = $_POST['parent'];
$name = $_POST['sub_menu_name'];
$role_id = $role_id1;
$menu_link = $_POST['sub_menu_link'];
$sql=$dbcon->query("INSERT INTO menu VALUES('','$name','$parent_id','$role_id','$menu_link')");
} 
?>
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Dropdown Menu</title>
<link rel="stylesheet" type="text/css" href="style.css" media="all" />
</head>
<body>
<div id="head">
<div class="wrap"><br />
<h1><a href="index.php">Back to menu</a></h1>
</div>
</div>
<center>
<pre>
<form method="post">
 <input type="text" placeholder="menu name :" name="menu name" /><br />
 <input type="text" placeholder="role id :" name="role_id" /><br />
 <input type="text" placeholder="menu link :" name="mn_link" /><br />
   <button type="submit" name="add_main_menu">Add main menu</button> 
 </form>
 </pre>
<br />
<pre>
<form method="post">
<select name="role_id">
<option selected="selected">select role id</option>
<?php
$res=$dbcon->query("SELECT distinct role_id FROM menu");
while($row=$res->fetch_array())
{
    ?>
     <option value="<?php echo $row['role_id']; ?>"><?php echo       $row['role_id']; ?></option>
<?php
 }
  ?>
  </select><br />
  <input type="submit" value="submit" name="submit">
<?php if(isset($_POST['submit']))
{
?>
 <select name="parent">
  <option selected="selected">select parent menu</option>
<?php
$role_id1 = $_POST['role_id'];
$res=$dbcon->query("SELECT * FROM menu where role_id= $role_id1 AND    parent_id=0 ");
 while($row=$res->fetch_array())
 {
?>
     <option value="<?php echo $row['id']; ?>"><?php echo $row['name']
;
?></option>
<?php

   }
   }

   ?>
  </select><br />
   <input type="text" placeholder="menu name :" name="sub_menu_name" /><br    />
   <input type="text" placeholder="menu link :" name="sub_menu_link" /><br />
   <button type="submit" name="add_sub_menu">Add sub menu</button>
 </form>
  </pre>
  <a href="index.php">back to main page</a>
  </center>
   </body>
    </html>
$role_id1 = $_POST['role_id'];

$role_id1的生存期是脚本停止(最后一行)和输出发送到浏览器(您再次看到表单)的位置。

因此,在代码顶部的行中:

$role_id = $role_id1;

$role_id1已经不存在了。如果查看错误日志(或打开 display_errors ),则会看到Notice: Undefined variable: role_id1 in ...

如果要保留该值,请将其放在隐藏元素中,以便在下次提交该表单时将其包含在 POST 数据中:

echo '<input type="hidden" name="previous_role_id" value="' . htmlspecialchars($_POST['role_id']) . '">';

一个旁注(为了完整起见),尽管元素是隐藏的,但用户可以更改该值。