当按下第二个提交按钮时,变量中的值将消失


Value in variable disappears when a second submit button is pressed

我的程序首先要求用户输入客户编号。这是在按下提交 1 按钮时实现的。然后,此客户编号用于从数据库中提取信息并显示它。然后必须更改此客户的地址,以便在第二个表单上要求此更改并按下提交 2 按钮。

问题是:

  1. 当按下提交 2 按钮时,客户不会从enter customer no框中消失,显示的信息也会消失。
  2. 变量$custno已失去其值。我需要这个变量来更新数据库。

为什么会这样?我什至在submit 1 REQUEST METHOD中使用了 POST,在submit 2 REQUEST METHOD中使用了 POST GET.

这是我使用的代码:

<!DOCTYPE html>
<html>
<body>
<?php
$custno=""; $custexists=1; // $custexists=1 means the customer exists in the database
$newaddress1=""; $newaddress2="";
if ($_SERVER["REQUEST_METHOD"] == 'POST' ) {
if (isset ($_POST["submit1"])) {$custno=$_POST["cust"];
goprintcust($custno,$custexists,$newaddress1,$newaddress2);}}
?>
<div style="position: fixed; left: 14px; top: 10px;">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<br>
<label>Enter Customer No. <input type="number" name="cust" min="1" value="<?php echo $custno; ?>"/></label>
<br>
<input type="submit" name="submit1" value="Submit 1"/><br>
</form>
<?php
function goprintcust($custno,$custexists,$newaddress1,$newaddress2) {
?><div style="position: relative; left: 8px; top:80px;"><?php
// Here search database for $custno and if it exists set $custexists=1
if ($custexists==1) {echo "current data for customer $custno is as follows ..."; // Print the current customer data from the database here
             getnewinput($newaddress1,$newaddress2);}} // we assume the customer exists in the database
                                   // so now get the new data to write into the database

function getnewinput($newaddress1,$newaddress2) {
?>
<div style="position: fixed; left: 14px; top: 60px;">
<table>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"">
<tr><td><label>New Address 1 :</td><td>  <input type="text" name="newaddress1" value="<?php echo $newaddress1; ?>"/></label></td></tr>
<br>
<tr><td><label>New Address 2 :</td><td>  <input type="text" name="newaddress2" value="<?php echo $newaddress2; ?>"/></label></td></tr>
<br>
<input type="hidden" name="cust" value="<?php echo $custno; ?>">
<tr><td><input type="submit" name="submit2" value="Submit 2"></td></tr><br>
</form>
</table>
<?php             }

if ($_SERVER["REQUEST_METHOD"]=="GET") {
if (isset ($_GET["submit2"])) {
$newaddress1=$_GET["newaddress1"]; $newaddress2=$_GET["newaddress2"];
getnewinput($newaddress1,$newaddress2);
?><div style="position: absolute; left: 8px; top:130px;"><?php
// Here write the new Address into the database              
echo "<br>"."Database updated for Customer No. ".$custno;
}}
?>
</body>
</html>

建议您将<input type="hidden" name="cust" value="<?php echo $custno; ?>">添加到第二个表单中。

当您提交第二个表单时,您的$_POST数组将被重置,这意味着$_POST['cust']不再存在。 否则$cust定义为空值。