在多个页面之间传递值php

时间:2017-06-01 17:15:29

标签: php

我正在使用2页。第1页,用户输入姓名和年龄。我已将表单操作作为同一页面,用户选择一个或两个占用,数据将被推送到第2页,显示所有结果。以下是相同的代码:

第1页:

<?php
echo "<form action=\"page1.php\" method=\"post\">";
echo "<h2>Your Name.  *</h2><input type='text' name='user_name'>";
echo "<br><br>";
echo "<h2>Your Age.  *</h2><input type='text' name='age'>";
echo "<br><br>";
echo "<div><input type='submit' value='Review'></div>";

?>

<?php
if((empty($_POST['user_name'])) || (empty($_POST['age'])) ) {
    echo "<h2>Please enter your user name and age</h2>";
} else {
    $user_name = $_POST['user_name'];
    $age = $_POST['age'];
    echo "<h2>Below are the details entered:</h2><br>";
    echo "<h2>Name: </h2>$user_name";
    echo "<h2>Age: </h2>$age";
    echo "<form action=\"page2.php\" method=\"post\">";
    echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox" 
      name="occupation[]" value="QA">QA</td>';
    echo '<td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox" 
      name="occupation[]" value="Tester">Tester</td>';
    echo "<br>";
    echo "<input type=\"submit\" value='Add to DB' >";
    echo "</form>";
}
?>

2页:

<?php
$user_name = $_GET['user_name'];
$age = $_GET['junos_version'];
$occupation = $_GET['occupation'];
echo "<h2>Below are the details entered:</h2><br>";
echo "<h2>Name: </h2>$user_name";
echo "<h2>Age: </h2>$age";
echo "<h2>Occupation selected: </h2>";
for ($i=0;$i<sizeof($occupation);$i++) {
    echo "  $occupation[$i]  ";
}   
?>

请帮助!!!

1 个答案:

答案 0 :(得分:0)

将所有字段放在一个表单中并验证操作或在前端开始之前将验证放入php中,我更喜欢第一个到您的情况,它更容易:

过滤行动

<?php
 if (empty($_POST['user_name'])){
       $action = 'page1.php';
       $structure = "<h2>Please enter your user name and age</h2>";
       $submit = 'Review';
  } else {
       $action = 'page2.php'; 
       $phrase = '';
       $user_name = $_POST['user_name'];
       $age = $_POST['age'];
       $structure = '<h2>Below are the details entered:</h2><br>
                     <h2>Name: </h2>$user_name
                      <h2>Age: </h2>$age
                       <td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox" name="occupation[]" value="QA">QA</td>
                       <td bgcolor="#EAEAEA" style="color:#003399"><input type="checkbox" name="occupation[]" value="Tester">Tester</td>';
echo "<br>";
       $submit = 'Add to DB';
  }

echo "<form action='{$action}' method=\"post\">";
echo "<h2>Your Name.  *</h2><input type='text' name='user_name'>";
echo "<br><br>";
echo "<h2>Your Age.  *</h2><input type='text' name='age'>";
echo "<br><br>";
echo $structure;
echo "<div><input type='submit' value='{$submit}'></div>";
echo "</form>";

?>
PS:避免所有这些回声,只需简单的html并在需要的地方使用php,它会更好。 TD的外围表格是完全错误的,然后删除,使用div代替并用CSS组织它们。