Solved

Redirect to previous page with previous entry in php

Posted on 2013-12-12
9
372 Views
Last Modified: 2013-12-13
Hi all.

I have 2 files: FieldSuperDataEntry.php and ProcessFieldSuperDataEntry.php

When the end user enters data in the data entry php page one of the fields they select is a builder---community from a drop down list. When they click the submit button it then goes to the ProcessFieldSuperDataEntry.php file where it inserts the data into a table, and at the end of that file it does a directs the user to the Menu.php file (header('Location: Menu.php');), at the end of the ProcessFieldSuperDataEntry.php file.

Instead I want to go back to the FieldSuperDataEntry.php file with the builder---community they had previously selected to be already selected in the drop down list, the rest of the data fields should be blank though.

How can I do this?

Thank you in advance.

FieldSuperDataEntry.php
<?php 
 
    require("common.php");

if(!$_SESSION['user']){
 header("Location: index.php");
 exit();
}

        
      $smt1 = $db1->prepare('SELECT FieldSuperAssignment.BuilderCommunityID,Builder, Community FROM BuilderCommunity INNER JOIN FieldSuperAssignment ON BuilderCommunity.BuilderCommunityID = FieldSuperAssignment.BuilderCommunityID   WHERE UserID = :user_id AND BuilderCommunity.Status = "Active" ORDER BY Builder, Community');

      $smt1->execute(array(':user_id' => $_SESSION['user']['userid']));
      $data1 = $smt1->fetchAll();
      
      $smt = $db-> prepare('SELECT jobtypeid, jobtypedescription FROM JobType ORDER BY jobtypeid');
      $smt->execute();
      $data = $smt->fetchAll();


$_SESSION['action_token'] = generate_secure_token(); 
?> 

<!DOCTYPE html>
<head>
  <title>MyApp</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <link rel="stylesheet" href="style.css" type="text/css" />
  <link href="iphone-icon1.png" rel="apple-touch-icon">
  <script>

function getLocation()
  {
  var options = {
  enableHighAccuracy: true,
  timeout: 60000,
  maximumAge: 0
};
  
  if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {  
  document.getElementById('Lat').value =position.coords.latitude
  document.getElementById('Long').value =position.coords.longitude
  }
  
  function checkFields()
  {
   var x = document.getElementById('lot').value;
   var y = document.getElementById('block').value;
    
    if((x=="" || x==" ") && (y=="" || y==" "))
    {
        alert("Please enter a lot and block number");
        return false;
    }
    
    else if(x=="" || x==" ")
    {
        alert("Please enter a lot number");
        return false;
    }
    
    else if(y=="" || y==" ")
    {
        alert("Please enter a block number");
        return false;
    }
        
    else return true;
  }
</script>

</head>
<body onload="getLocation()">
<?php echo "User: " . $_SESSION['user']['Name'] ?>
<div class="wrapper">
    <div id="logo"></div>
    
   <form class="form4" action="ProcessFieldSuperDataEntry.php" method="post">
<div class="formtitle4">Data Entry</div>

    		
           
    		<div class="input2">
                 <div class="inputtext">Builder/Community:</div>           
                 	<div class="inputcontent" ><select name="BuilderCommunity" id="BuilderCommunity" style="width: 250px"><option selected="selected"></option>    
                
                <?php foreach($data1 as $row) { printf("<option value='%s'>%s --- %s </option>", html_escape($row['BuilderCommunityID']), html_escape($row['Builder']), html_escape($row['Community'])); }?>
                 	</select></div>
                </select>
                <br>
                <br>
                <br>
           
                <div class="inputtext">Lot:</div> 
    			<div class="inputcontent" ><input name="lot" id="lot" input type="text" />
               
				</div>
                
                <div class="inputtext">Block:</div>
               <div class="inputcontent" >

    			    <input name="block" id="block" input type="text" />

				</div>
               
		  </div>  
            
            <div class="input2"> 
            	<div class="inputtext">Type:</div>           
                 	<div class="inputcontent" ><select name="type" id="type" style="width: 20em;"><option selected="selected"> </option>    
                     <?php foreach($data as $row) { printf("<option value='%s'>%s</option>", html_escape($row['jobtypeid']), html_escape($row['jobtypedescription']) ); }?>

				 		</select>
				 	</div>
			     
  
            </div>            
            

			<div class="input nobottomborder">
				<div class="inputtext">Notes: </div>
				<div class="inputcontent">
					<textarea name="notes" id = "notes" rows = "3" cols = "80"></textarea>	                			
				</div>
			</div>
        <input type="hidden" name="action_token" value="<?php echo html_escape($_SESSION['action_token']) ?>" />
        <input type = "hidden" input name = "Lat" input id = "Lat"><br>
        <input type = "hidden" input name = "Long" input id = "Long"><br>
     
			<div class="buttons" align = center>

				<input class="button1"  type="submit" value="Save" onclick="return checkFields()" />
				<input class="button1"  type="submit" formaction="Menu.php" value="Menu" /> 

		
			</div>


</form>
</body>
</html>

Open in new window


ProcessFieldSuperDataEntry.php
<?php 
   
    require("common.php");

 $date = new DateTime();
              $date->setTimezone(new DateTimeZone('America/New_York'));
              $fdate = $date->format('Y-m-d H:i:s');
              $date2 = new DateTime();  // This date and time variable will be used to display it to the end user as 3:50 PM but it will be saved in the table as a 24 hour format in $fdate
              $date2->setTimezone(new DateTimeZone('America/New_York'));
              $fdate2 = html_escape($date2->format('m/d/Y h:i:s A')); 
  $query = " 
            SELECT 
                1 
            FROM FieldSuperDataEntry 
            WHERE 
                BuilderCommunityID = :buildercommunityid AND Lot = :lot AND Block = :block
        "; 

  $query_params = array( 
            ':buildercommunityid' => $_POST['BuilderCommunity'] ,
            ':lot' => $_POST['lot'],
            ':block' => $_POST['block']
        ); 
        
           $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
            
            $row = $stmt->fetch();
            
        if($row) 
        { 
  $query = " 
            SELECT 
                1 
            FROM FieldSuperDataEntry 
            WHERE 
                BuilderCommunityID = :buildercommunityid AND Lot = :lot AND Block = :block
        "; 

  $query_params = array( 
            ':buildercommunityid' => $_POST['BuilderCommunity'] ,
            ':lot' => $_POST['lot'],
            ':block' => $_POST['block']
        ); 
        
           $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
            
            $row = $stmt->fetch();
            
        if($row) 
        { 
  $query = " 
            SELECT 
                1 
            FROM FieldSuperDataEntry 
            WHERE 
                BuilderCommunityID = :buildercommunityid AND Lot = :lot AND Block = :block
        "; 

  $query_params = array( 
            ':buildercommunityid' => $_POST['BuilderCommunity'] ,
            ':lot' => $_POST['lot'],
            ':block' => $_POST['block']
        ); 
        
           $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
            
            $row = $stmt->fetch();
            
        if($row) 
        { 
 echo '<script type="text/javascript">alert("That Builder/Community/Lot/Block has already been entered.");</script>'; 
          echo '<script type="text/javascript">window.location.href = "http://www.myapp.com";</script>';

  exit();
        }

        
        $query = " 
            INSERT INTO FieldSuperDataEntry ( 
                BuilderCommunityID, 
                Lot, 
                Block,
                Type,
                Latitude,
                Longitude,
                Notes,
                UserID,
                CreateDate,
                ModifiedDate
            ) VALUES ( 
                :buildercommunityid, 
                :lot, 
                :block,
                :type,
                :latitude,
                :longitude,
                :notes,
                :userid,
                :currentdatetime,
                :modifieddatetime
             ) 
        "; 
   $query_params = array( 
            ':buildercommunityid' => $_POST['BuilderCommunity'], 
            ':lot' => $_POST['lot'], 
            ':block' => $_POST['block'], 
            ':type' =>$_POST['type'],
            ':latitude' => $_POST['Lat'],
            ':longitude' => $_POST['Long'],
            ':notes' => $_POST['notes'],
            ':userid' => $_SESSION['user']['userid'] ,
            ':currentdatetime' => $fdate,
            ':modifieddatetime' => $fdate
          ); 
         
     
            // Execute the query to insert data into the FieldSuperDataEntry table 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params);
        unset( $_SESSION['action_token'] );
        header('Location: Menu.php');
        exit();

Open in new window

0
Comment
Question by:Sim1980
  • 4
  • 3
  • 2
9 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
You can keep the data in the PHP session and use it to populate the HTML document with the appropriate selections.  Please read this article and post back if you still have any questions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11909-PHP-Sessions-Simpler-Than-You-May-Think.html
0
 

Author Comment

by:Sim1980
Comment Utility
How do I tell the BuilderCommunity drop down to select the BuilderCommunityID in the session?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
It looks like the options are created at line 94 and 118.  You would want to expand that PHP code to compare the options from the data base to the data, if any, that was stored in the session by the action script.  On the match, you would mark the option "selected."  

You might want to remove the information from the session when you use it to prepopulate the form.  I'm not sure about that, it would be a business logic question you would want to answer.

You would also want to change the URL for the header() that redirects in the bottom of the action script.
0
 

Author Comment

by:Sim1980
Comment Utility
Ok I tried the following, but it is not selecting the buildercommunity that I originally selected:

    <div class="inputtext">Builder/Community:</div>           
                 	<div class="inputcontent" ><select name="BuilderCommunity" id="BuilderCommunity" style="width: 250px">   
                
                <?php foreach($data1 as $row) { printf("<option value='%s' selected>%s --- %s </option>", html_escape($row['BuilderCommunityID']) == $_SESSION['buildercommunityid'], html_escape($row['Builder']), html_escape($row['Community'])); }?>
                
                 	</select></div>

Open in new window

0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
You may have to get some PHP education to be able to get this right.  I don't think there is any way I can write code for you because I do not have a test data set.  But maybe I can come up with some kind of a demonstration script that illustrates the principles in a "teaching example."
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 250 total points
Comment Utility
You want to do something like this

Note you see to have validation issue on lines 95 and 96 - you are closing the </select twice - remove line 96
In your ProcessFieldSuperDataEntry.php file
<?php
session_start();

$_SESSION['BuilderCommunity'] = isset($_POST['BuilderCommunity']) ?
   $_POST['BuilderCommunity'] : 
?>

Open in new window

And in FieldSuperDataEntry.php
<?php
session_start();
$buildingcommunity = isset($_SESSION['BuilderCommunity']) ? 
  $_SESSION['BuilderCommunity'] :
  ''; 

<div class="inputcontent" >
  <select name="BuilderCommunity" id="BuilderCommunity" style="width: 250px">
    <option selected="selected"></option>    
<?php foreach($data1 as $row) : 
	$selected = (row['BuilderCommunityID'] == $buildingcommunity) ?
          ' selected="selected" : 
          '';
	printf("<option value='%s'%s>%s --- %s </option>", html_escape($row['BuilderCommunityID']), $selected, html_escape($row['Builder']), html_escape($row['Community'])); 
endforeach;
?>
  </select>
</div>

Open in new window

Some comments on the above

1. I have used the foreach () : endforeach instead of curly braces. When mixing code and html I find this easier to identify closing blocks.

2. I have added a line to set a value selected which gets set to the string ' selected="selected"' or an empty string depending on whether the BuilderCommunityID of the current row in the loop is the same as the previously selected value. To keep in line with validation requirements for HTML5 I have put the full string not just the value 'selected'.

Give that a try and see how you get on.
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
Taken together, these two simplified scripts illustrate the design principle.

The form script:
<?php // RAY_temp_sim1980_form.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28316674.html#a39714603
// FORM SCRIPT USES "REMEMBERED" CLIENT SELECTIONS, IF ANY,
// FROM PRIOR SUBMISSIONS OF THE FORM


// BOTH SCRIPTS USE THE SESSION
session_start();

// HERE ARE THE VALID CHOICES (MUST BE KNOWN TO BOTH SCRIPTS)
$colors = array
( 'red'
, 'blue'
, 'green'
);

// WHAT COLOR DID THE ACTION SCRIPT REMEMBER?
$color = !empty($_SESSION['color']) ? $_SESSION['color'] : NULL;

// GENERATE THE SELECT OPTIONS
$opts = NULL;
foreach ($colors as $option)
{
    $selected = NULL;
    if ($option == $color) $selected = 'selected ';
    $opts .= '<option value="' . $option . '" ' . $selected . '>' . $option . '</option>' . PHP_EOL;
}

// GENERATE THE FORM
$form = <<<EOD
<form method="post" action="RAY_temp_sim1980_action.php">
<select name="color">
$opts
</select>
<input type="submit" />
</form>
EOD;

echo $form;

Open in new window

The action script:
<?php // RAY_temp_sim1980_action.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_28316674.html#a39714603
// ACTION SCRIPT SAVES CLIENT SELECTIONS SO THAT THEY CAN BE "REMEMBERED"
// WHEN THE CLIENT USES THE BACK BUTTON TO REVISIT THE FORM


// BOTH SCRIPTS USE THE SESSION
session_start();

// HERE ARE THE VALID CHOICES (MUST BE KNOWN TO BOTH SCRIPTS)
$colors = array
( 'red'
, 'blue'
, 'green'
);

// WHAT COLOR DID THE CLIENT CHOOSE (FILTER, SANITIZE HERE)
$color = !empty($_POST['color']) ? $_POST['color'] : NULL;

// IS THE SELECTION PRESENT AND VALID?
if ($color)
{
    if (in_array($color, $colors))
    {
        // VALID SELECTION -- REMEMBER IT
        $_SESSION['color'] = $color;
    }
    else
    {
        // NOT A VALID SELECTION?  PROBABLY A HACKER
        trigger_error('SCRIPT UNDER ATTACK, RUN LIKE HELL', E_USER_ERROR);
    }

    // SCRIPT IS COMPLETE
    echo "THANK YOU FOR CHOOSING $color";
}
else
{
    echo "YOU DID NOT CHOOSE ANY COLOR";
}

Open in new window

HTH, ~Ray
0
 

Author Closing Comment

by:Sim1980
Comment Utility
Thank you both!
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome - thanks for the points.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
This article discusses how to create an extensible mechanism for linked drop downs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now