douwen4125 2016-10-03 20:09
浏览 80

在PHP中使用会话数据

I'm having a difficult time understanding the $_SESSION function in PHP. I'm building a multipage form and when it was a single form, everything worked as expected. Now I'm trying to figure out $_SESSION so that data from page1 carries to page2 for the submit.

So here is page 1:

<?php require_once("../tim/includes/validation_functions.php");
      include("../tim/includes/session.php"); 
      require_once("../tim/includes/variables.php"); 
      include ("/testing/tim/obervation-upload.php"); 
 ?>
<?php
session_start(); // Session starts here.
?>
<!DOCTYPE HTML>
<html lang="en">
    <head>
    <link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
      <script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>

    <title>Assessment Application</title>
    </head>
    <body>
<div>
<h2>3SP Assessment</h2>     
<span id="error">
 <!---- Initializing Session for errors --->
 <?php
 if (!empty($_SESSION['error'])) {
 echo $_SESSION['error'];
 unset($_SESSION['error']);
 }
 ?>
 </span>

<form class="form-horizontal" role="form" name="assessment" action="application_form.php" method="post">
<div class="form-group" style="margin-bottom:10px;">
<label for="company_name" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Company name:</strong></label>
<div class="col-md-2"> <input type="text" id="company_name" name="company_name"  class="form-control" required> </div>
  <div class="clearfix"></div>
<label for="date" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Date:</strong></label>
 <div class="col-md-2"><input type="date" name="date" id="date" class="form-control" required> </div>
 <div class="clearfix"></div>
 <label for="rsm" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Regional Sales Manager:</strong></label>
<div class="col-md-2"> <input type="text" name="rsm" id="rsm" class="form-control" required></div>
<div class="clearfix"></div>
<label for="agents" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Agents:</strong> </label>
<div class="col-md-2"> <input type="text" name="agents" id="agents" class="form-control" required></div>
<div class="clearfix"></div>
<label for="distributor" class="col-lg-1 col-md-2 col-sm-4 control-label"><strong>Distributor:</strong> </label>
<div class="col-md-2"><input type="text" name="distributor" class="form-control" required></div>
</div>

<p style="margin-left:5px;"><input class="btn btn-danger" type="reset"> 
<input style="margin-left:10px;" class="btn btn-success" type="submit" value="Next" /></p>
</form>

<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>


    </body>
</html>

page 2:

<?php require_once("../tim/includes/validation_functions.php");
      include("../tim/includes/session.php"); 
      require_once("../tim/includes/variables.php"); 
      include ("/testing/tim/obervation-upload.php"); 
 ?>
<?php
session_start();
 foreach ($_POST as $key => $value) {
 $_SESSION['post'][$key] = $value;
 }
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="/testing/tim/bootstrap-theme.min.css">
      <script type="text/javascript" src="/testing/tim/js/jquery-3.1.0.min.js"></script>
    <script type="text/javascript" src="/testing/tim/js/bootstrap.min.js"></script>


    <title>Assessment Application</title>
    </head>
    <body>

<div>
<h2>3SP Assessment</h2>     

<form name="assessment" action="create_new_record.php" method="POST" enctype="multipart/form-data">
<p>Department name: <input type="text" name="department_name"  /> </p>
<p>Participant name: <input type="text" name="participant_name" /> </p>
<p>Activity performed: <textarea cols="25" rows="3" name="activity" ></textarea> </p>
<p>Location: <input type="text" name="location"  /> </p>
<p>Conditon: <select class="form-control" name="condition" style="width:20%;">
  <option value="dry" id="dry">Dry</option>
  <option value="heavy_oil" id="heavy_oil">Heavy Oil/Grease</option>
  <option value="light_oil" id="light_oil">Light Oil</option>
  <option value="sandy" id="sandy">Sandy/Grit</option>
  <option value="wet" id="wet">Slightly Wet</option>
</select></p>

<div class="well">
<p>Avg Number of Recordable Injuries:
<input type="number" name="injuries" />
 <select name="injury_time_frame">
       <option value="last month">Last month</option>
   <option value="last 6 months">Last 6 months</option>
   <option value="last 12 months">Last 12 months</option>
  </select>
</p>

<h4>Based on the number of Recordable Injuries - Estimate the Injury Type by Percentage </h4> 
<div class="container-fluid">
  <div class="form-group row">
    <div class="col-md-3 col-sm-4"><input class="form-control" id="cuts" name="cuts" type="number" min="0" max="100"  value="" placeholder="Cuts / Lacerations / Abrasion" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="burns" name="burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="infection" name="infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="dermatitis" name="dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
    <div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="puncture" name="puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="sprain" name="sprain" type="number" min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" id="impact" name="impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" /> </div>
  </div>
</div>
<p id="rec_injuries"></p>
<script>
function percentageTest() {

    // Get the value of the input fields
    a = document.getElementById("cuts").value;
    b = document.getElementById("burns").value;
    c = document.getElementById("infection").value;
    d = document.getElementById("dermatitis").value;
    e = document.getElementById("puncture").value;
    f = document.getElementById("sprain").value;
    g = document.getElementById("impact").value;

    var x = (a + b + c + d + e + f + g);

    // grouping together and doing the math
    if (x = !100) {
        text = "The total percentage must equal 100%";
    } else {
        text = "Congrats the total = 100%";
    }
    document.getElementById("rec_injuries").innerHTML = text;
}
</script>
</div>

<div class="well">
<p>Avg Number of Non-recordable Injuries: <input type="number" name="non_rec_injuries" />
 <select name="non_rec_injury_timeframe">
    <option value="last month">Last month</option>
    <option value="last 6 months">Last 6 months</option>
    <option value="last 12 months">Last 12 months</option>
 </select>
</p>
<h4>Based on the number of Non-recordable Injuries - Estimate the Injury Type by Percentage </h4>
<div class="container-fluid">
  <div class="form-group row">
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_cuts" type="number" min="0" max="100" value="" placeholder="Cuts / Lacerations / Abrasion" /> </div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_burns" type="number" min="0" max="100" value="" placeholder="Heat or Chemical Burn" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_infection" type="number" min="0" max="100" value="" placeholder="Infection" /> </div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_dermatitis" type="number" min="0" max="100" value="" placeholder="Dermatitis" /> </div>
    <div class="clearfix visible-xs-block"></div> <div class="hidden-xs hidden-sm"><br /><br /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_puncture" type="number" min="0" max="100" value="" placeholder="Puncture" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_sprain" type="number"  min="0" max="100" value="" placeholder="Carpal Tunnel / Sprain" /></div>
    <div class="col-md-3 col-sm-4"><input class="form-control" name="non_rec_impact" type="number" min="0" max="100" value="" placeholder="Impact / Contusion / Inflammation" />
    </div>
  </div>
</div>
</div>

<p>Estimated Cost of Productivity (Downtime)/minute: $ <input type="number" name="cost_of_productivity" /> </p>
<p>Percent of leakage related to uncontrolled dispensing: <input type="number" min="0" max="100" name="leakage" /> % </p>
<p>Which competitor is the participant using?  <input type="text" name="competitor" /></p>
<p>Usage Rate per 12 months (pairs): <input type="number" min="0" name="usage_rate" /></p>
<p>Estimated cost per pair: $ <input type="number" min="0" name="cost_per_pair" /></p>
<br />  
<div class="container" style="margin-left:0px; padding-left:0px;">
<div class="form-group row" style="margin-left:0px;">

<div class="col-md-3 col-sm-6">
<label for="safetyHazard1_notes"><strong>Safety observation 1:</strong></label>  <input type="file" name="safetyHazard1" id="safetyHazard1" value=""><br /> <br />
<textarea cols="25" rows="3" id="safetyHazard1_notes" name="safetyHazard1_notes" placeholder="Enter notes for this observation" ></textarea> </div>

<div class="col-md-3 col-sm-6">
<label for="safetyHazard2_notes"><strong>Safety observation 2:</strong></label> <input type="file" name="safetyHazard2" id="safetyHazard2" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>

<div class="col-md-3 col-sm-6">
<label for="safetyHazard3_notes"><strong>Safety observation 3:</strong></label> <input type="file" name="safetyHazard3" id="safetyHazard3" value=""><br /><br />
<textarea cols="25" rows="3" id="safetyHazard2_notes" name="safetyHazard2_notes" placeholder="Enter notes for this observation" ></textarea> </div>


<div class="col-md-3 col-sm-6">
<label for="other_notes"><strong>Other observations:</strong></label> <input type="file" name="otherObservation" id="otherObservation" value=""><br /><br />
<textarea cols="25" rows="3" id="other_notes" name="other_notes" placeholder="Enter notes for this observation" ></textarea> </div>
</div></div>
<br />

<p style="margin-left:5px;"><input class="btn btn-danger" type="reset"> 
<input style="margin-left:10px;" class="btn btn-primary" type="button" name="new_location" value="Add Additional Location" />
<input style="margin-left:10px;" class="btn btn-success" type="submit" name="submit" value="Create New Assessment" /></p>
</form>

<p class="pull-left"><a type="button" class="btn btn-default" href="http://us.pipglobal.com/en/" target="_blank">Cancel</a></p>
</div>


    </body>
</html>

And finally the processing page:

<?php
require_once("../tim/includes/session.php"); 
require_once ("../tim/includes/functions.php");
require_once("../tim/includes/validation_functions.php"); 
?>

<?php
if(isset($_POST["submit"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . '/testing/tim/uploads/';
$target_file = $target_dir . basename($_FILES["safetyHazard1"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if image file is a actual image or fake image
    $check = getimagesize($_FILES["safetyHazard1"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Check file size
if ($_FILES["safetyHazard1"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["safetyHazard1"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["safetyHazard1"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
foreach ($_POST as $key => $value) {
 $_SESSION['post'][$key] = $value;
 } 
  extract($_SESSION['post']);

    // Process the form
    $department_name = ($_POST['department_name']);
    $participant_name = ($_POST['participant_name']);
    $activity = ($_POST['activity']);
    $location = ($_POST['location']);
    $rec_injuries = ($_POST['injuries']);
    $rec_injuries_timeframe = ($_POST['injury_time_frame']);
    $non_rec_injuries = ($_POST['non_rec_injuries']);
    $non_rec_injuries_timeframe = ($_POST['non_rec_injury_timeframe']);
    $rec_cuts = ($_POST['cuts']);
    $rec_burns = ($_POST['burns']);
    $rec_infection = ($_POST['infection']);
    $rec_dermatitis = ($_POST['dermatitis']);
    $rec_puncture = ($_POST['puncture']);
    $rec_sprain = ($_POST['sprain']);
    $rec_impact = ($_POST['impact']);
    $non_rec_cuts = ($_POST['non_rec_cuts']);
    $non_rec_burns = ($_POST['non_rec_burns']);
    $non_rec_infection = ($_POST['non_rec_infection']);
    $non_rec_dermatitis = ($_POST['non_rec_dermatitis']);
    $non_rec_puncture = ($_POST['non_rec_puncture']);
    $non_rec_sprain = ($_POST['non_rec_sprain']);
    $non_rec_impact = ($_POST['non_rec_impact']);
    $cost_of_productivity = ($_POST['cost_of_productivity']);
    $leakage = (($_POST['leakage']) / 100);
    $usage_rate = ($_POST['usage_rate']);
    $cost_per_pair = ($_POST['cost_per_pair']);
    $condition = ($_POST['condition']);
    $safety_hazard_1 = basename( $_FILES["safetyHazard1"]["name"]);
    $safety_hazard_2 = ($_POST['safetyHazard2']);
    $safety_hazard_3 = ($_POST['safetyHazard3']);
    $other_observation = ($_POST['otherObservation']); 
    $safetyHazard1_notes = ($_POST['safetyHazard1_notes']);
    $safetyHazard2_notes = ($_POST['safetyHazard2_notes']);
    $safetyHazard3_notes = ($_POST['safetyHazard3_notes']);
    $otherNotes = ($_POST['otherNotes']); 
    $competitor = ($_POST['competitor']);
    $company_name = ($_POST['company_name']);
    $date = ($_POST['date']);
    $rsm = ($_POST['rsm']);
    $agents = ($_POST['agents']);
    $distributor = ($_POST['distributor']);

  print "distributor: " . $distributor;
  exit;
    // Perform first database insert    
    $query1  = "INSERT INTO location_info (";
    $query1 .= "`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `safety_hazard_1`, `safety_hazard_2`, `safety_hazard_3`, `other_observation`,`safetyHazard1_notes`, `safetyHazard2_notes`, `safetyHazard3_notes`, `otherNotes`";
    $query1 .= ") VALUES (";
    $query1 .= "  '{$department_name}', '{$participant_name}', '{$activity}', '{$location}', '{$rec_injuries}', '{$rec_injuries_timeframe}', 
    '{$non_rec_injuries}', '{$non_rec_injuries_timeframe}', '{$competitor}', '{$cost_per_pair}', '{$usage_rate}', '{$leakage}', '{$cost_of_productivity}', '{$non_rec_impact}', '{$non_rec_sprain}', '{$non_rec_puncture}', '{$non_rec_dermatitis}', '{$non_rec_infection}', '{$non_rec_burns}', '{$non_rec_cuts}', '{$rec_impact}', '{$rec_sprain}', '{$rec_puncture}', '{$rec_dermatitis}', '{$rec_infection}', '{$rec_burns}', '{$rec_cuts}', '{$condition}', '{$safety_hazard_1}', '{$safety_hazard_2}', '{$safety_hazard_3}', '{$other_observation}','{$safetyHazard1_notes}', '{$safetyHazard2_notes}', '{$safetyHazard3_notes}', '{$otherNotes}'";
    $query1 .= ")";
    $result1 = mysqli_query($connection, $query1);

    if ($result1) {
        // Success

    $_SESSION["message"] = "Assessment created.";
        redirect_to("results.php");
    } else {
        // Failure
        $_SESSION["message"] = "Assessment creation failed.";
        redirect_to("errors.php");
            }   

    // Perform second database insert   
    $query2  = "INSERT INTO general_assessment (";
    $query2 .= "`company_name`, `date`, `rsm`, `agents`, `distributor`";
    $query2 .= ") VALUES (";
    $query2 .= "  '{$company_name}', '{$date}', '{$rsm}', '{$agents}', '{$distributor}'";
    $query2 .= ")";
    $result2 = mysqli_query($connection, $query2);

    if ($result2) {
        // Success

    $_SESSION["message"] = "Assessment created.";
        redirect_to("results.php");
    } else {
        // Failure
        $_SESSION["message"] = "Assessment creation failed.";
        redirect_to("errors.php");
            }   
}
else {
    redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/errors-inserting.php"); 
}
?>

<?php
    if (isset($connection)) { mysqli_close($connection); }
?>

You'll see on the processing page my little test of

print "distributor: " . $distributor;
  exit;

this would obviously be removed when working.

  • 写回答

3条回答 默认 最新

  • douduiwei2831 2016-10-03 20:13
    关注

    You have to use line session_start(); on every page that you want to use the session - as the first line on top of the file.

    You can set variables:

    $_SESSION['username'] = "user";
    

    and then retrieve them:

    echo $_SESSION['username'];
    

    You can then use session_destroy() to remove the saved session

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料