Solved

Redirect to previous page with previous entry in php

Posted on 2013-12-12
9
374 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
ID: 39714472
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
ID: 39714583
How do I tell the BuilderCommunity drop down to select the BuilderCommunityID in the session?
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39714603
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
ID: 39714709
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39715498
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 52

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 39716278
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
ID: 39716692
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
ID: 39716989
Thank you both!
0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 39717462
You are welcome - thanks for the points.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Finding (and replacing) text between two strings in Php 7 50
File submission to SQL Server 1 35
Create a Select Query and Populate a Table 3 43
Download a website to hdd 2 47
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

948 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

18 Experts available now in Live!

Get 1:1 Help Now