Solved

Calculations in a multi page form in PHP

Posted on 2013-02-04
14
492 Views
Last Modified: 2013-02-15
Hello all experts.

I am presently custom coding a form in a  PHP website. It has a multi page form. In few fields on the form user has to enter data. Based on data entered some fields calculate and populate automatically.  I have included the calculation in PHP code and come across one challenge.

For one particular filed the calculation is
If x-y >0 then echo x-y =z  else y

X is a value in a field entered by the user
Y is a value taken from DB

My issue is how do I take one value from the filed of the form and other from DB in the same calculation, show the result in desired filed of the same form and then later save the result filed vale in a session variable?

 <td class="form_input">
   <input type="text" name="countable_equity" id="countable_equity" readonly="readonly" size="30"  class="required number" value="<?php if(!$_SESSION['married']&&$_SESSION['single']['dependent_spouse']!="yes")
{
    if(($_POST['primary_residence']-$csra_max)>0)
{
  echo $_POST['primary_residence']-$csra_max;}
              
  else{
              echo '0';}}?>
/>
                        </td>

Open in new window

0
Comment
Question by:shawnlearn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 5
  • 2
  • +1
14 Comments
 
LVL 7

Expert Comment

by:karunamoorthy
ID: 38850392
just to ensure the values entered by user is assigned or not
by using simple echo statement will do a favor to you

above this line ( if(($_POST['primary_residence']-$csra_max)>0) )

echo  $_POST['primary_residence'] ;
echo '\n';
echo $csra_max;

Now you debug yourself without much difficulty.
The best debugging tool is here
================================
If in doubt use,  echo statement
================================

Have a good day!
0
 
LVL 1

Author Comment

by:shawnlearn
ID: 38850741
Now you debug yourself without much difficulty.
The best debugging tool is here
================================
If in doubt use,  echo statement
================================


I appreciate your response but I don't want to debug or check. I want to know how to do this in first place. I have written a code but that isn't working. Reason : one vale of  field is on form and one one vale is coming from DB , in such a case how to calculate it? I need help as to what is wrong with my code snippet above.

Thanks,
Shawn
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38850861
The values from the data base can be retrieved at any time with a query.  At the start of your "action" script (the script that processes the submitted form) get the values from the data base and store these values in variables.  Next, find the other values in the $_POST array.  Then make the computation.  Obviously this can only be completed after the client submits the form.

If you follow that design and you're still having troubles, please post an SSCCE example showing the issue and I'll try to help.
0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 
LVL 20

Assisted Solution

by:Mark Brady
Mark Brady earned 250 total points
ID: 38850900
The way I understand the question is the user will fill out an area of the form and before they submit it, there will need to be a db lookup to get a value then a comparison made, finally the result goes into another field on the same form. This final value will be submitted once the form is complete.

It would be good if you could give us a few examples of data that could be entered, how the db query would look and the result you want to see.

Basically, you would need to utilised the onBlur() event handler and have that run a function to make your ajax call, sending the parameters from the form the user has already filled out.

On the response javascript can take the returned value and load it into the correct field for you. Pretty straight forward stuff.


Any examples you can give would be benificial
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38854497
@elvin66: I thought of that, too, and it's certainy a workable idea - maybe use jQuery and AJAX to call the data base lookup script when the value is filled in the form.  But I also wondered, "Why not look up the value from the data base before the form script is presented to the client?"  Since it is described as a multi-page form, it would seem that some part of the form is submitted before the rest of the form is presented.  If the application captures enough identifying information in the first form submission to read the correct data from the data base, the whole design gets easier.
0
 
LVL 1

Author Comment

by:shawnlearn
ID: 38854605
Ray I am storing data of multipage form in a session and then later feeding it in DB in one go in the end of form.

I have got the basic idea from elvin but I think because I have never done it before I am still confused. I tried doing it that way but couldn't figure it out exactly.

I have posted a SSCCE example of code, highly appreciate your help on this. In form 2 csra_max is coming from DB.

Page 1 form. I ask user if he's married or single and collect basic data.

<?php

if(!is_user_logged_in()){
    wp_redirect(esc_url( home_url( '/' )));
}
get_header(); ?>
<script type="text/javascript">
    $(document).ready(function(){
        $(".single").hide();
    });
    function first(){
        $(".married").fadeIn("normal");
        $(".single").hide();
    }
    function second(){
        $(".single").fadeIn("normal");
        $(".married").hide();
    }
</script>
<?php 
session_start();
if(isset($_SESSION['register'])){
    unset($_SESSION['register']);
}
global $wpdb;
$query = 'SELECT id ,state FROM '.$wpdb->prefix.'fxxx_stxxxxdata ORDER BY id DESC';  
$StateRecords=$wpdb->get_results($query);

?>
<link href="<?php bloginfo('template_url'); ?>/scripts/tcal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<?php bloginfo('template_url'); ?>/scripts/tcal.js"></script> 
<div class="whitebox">
    <div class="whiteboxtop"></div>
    <form action="<?php echo get_permalink(337); ?>" method="post" id="commentForm">
        <div class="mainwrapperfin">
            <h3>form 2</h3>
            <div id="marital_status">
                <p>Select status:</p>
                <div>
                    <input type="radio" checked="checked" name="form_type" value="married" onclick="first();">
                    <label for="form_type" TABINDEX=1>Married</label>
                    <input type="radio"  name="form_type"  value="personel"  onclick="second();" >
                    <label for="form_type" TABINDEX=2>Single</label>
                </div>
            </div>
            <table class="married">
                <tr>
                    <td class="form_text">Husband:</td>
                    <td class="form_input">
                        <input name="husband_name" type="text" size="30" value="<?php echo $_SESSION['married']['husband_name'];?>" class="required" TABINDEX=3/>
                    </td>
                    <td class="form_text">Husband DOB:</td>
                    <td class="form_input">
                        <input name="husband_dob" TABINDEX=4 type="text" size="12" value= "<?php echo $_SESSION['married']['husband_dob'];?>" class="tcal required date"  style="width:180px;"/>
                    </td>
                </tr>
                <tr>
                    <td class="form_text">Wife:</td>
                    <td class="form_input">
                        <input TABINDEX=5 name="wife_name" type="text" class="required" size="30" value="<?php echo $_SESSION['married']['wife_name'];?>"/>
                    </td>
                    <td class="form_text">Wife DOB:</td>
                    <td class="form_input">
                        <input TABINDEX=6 name="wife_dob" type="text" size="12" class="tcal required date" value="<?php echo $_SESSION['married']['wife_dob'];?>" style="width:180px;"/>
                    </td>
                </tr>
                <tr>
                    <td class="form_text">State</td>
                    <td class="form_input">
                        <select name="residence_state_married" TABINDEX=7>
                            <?php foreach($StateRecords as $state): ?>
                                <option value="<?php echo $state->id;?>" <?php if($_SESSION['married']['residence_state']==$state->id){ echo 'selected="selected"';}?>> <?php echo $state->state;?> </option>
                            <?php endforeach; ?> 
                        </select>
                    </td>
                    <td class="form_text">Dependent:</td>
                    <td class="form_input">
                        <select name="dependent_spouse_married" TABINDEX=8>
                            <option value="yes" <?php if($_SESSION['married']['dependent_spouse']=='yes') {  echo 'selected=selected';}?>>Yes</option>
                            <option value="no" <?php if($_SESSION['married']['dependent_spouse']=='no') {  echo 'selected=selected';}?>>No</option>
                        </select>
                    </td>
                </tr>
            </table>                     
    <!-- personel -->
            <table class="single">
                <tr>
                    <td class="form_text">Name:</td>
                    <td class="form_input">
                        <input TABINDEX=1 type="text" size="30" value="<?php echo $_SESSION['single']['single_name'];?>" class="required" name="single_name"/>
                    </td>
                    <td class="form_text">Date of Birth:</td>
                    <td class="form_input">
                        <input TABINDEX=2 type="text" size="12" value= "<?php echo $_SESSION['single']['single_dob'];?>" class="tcal" name="single_dob" style="width:180px;"/>
                    </td>
                </tr>
                <tr>
                    <td class="form_text">State:</td>
                    <td class="form_input">
                        <select name="residence_state_single" TABINDEX=3>
                            <?php foreach($StateRecords as $state): ?>
                                <option value="<?php echo $state->id;?>" <?php if($_SESSION['single']['residence_state']==$state->id){ echo 'selected=selected';}?>><?php echo $state->state;?></option>
                            <?php endforeach;?> 
                        </select>
                    </td>
                    <td class="form_text">Dependents :</td>
                    <td class="form_input" TABINDEX=4>
                        <select name="dependent_spouse_single">
                            <option value="yes" <?php if($_SESSION['single']['dependent_spouse']=='yes') {  echo 'selected=selected';}?>>Yes</option>
                            <option value="no" <?php if($_SESSION['single']['dependent_spouse']=='no') {  echo 'selected=selected';}?>>No</option>
                        </select>
                    </td>     
                </tr>
            </table>    
            <input type="submit" class="nextbutton" name="submit_personal" value="Next"/>
    </div>
    </form>

Open in new window



Page 2

<?php

if(!is_user_logged_in()){
    wp_redirect(esc_url( home_url( '/' )));
}
get_header();
session_start();
global $wpdb;

if($_SESSION['single']){ 
$query='SELECT * FROM '.$wpdb->prefix.'fixxx_stxxxa WHERE id='.$_SESSION['single']['residence_state'];
$result=$wpdb->get_results($query);
$result=$result[0];
$csra_max=$result->csra_max;

}

$result=$wpdb->get_results($query);
if(isset($_POST['submit_personal']))
 {
     if($_POST['form_type']=='married') 
   {
          if(isset($_SESSION['single']))
     {
               unset($_SESSION['single']);
               unset($_SESSION['facts']);
           }
         $_SESSION['married']=array(
            'husband_name'=>trim(htmlspecialchars($_POST['husband_name'])),
            'husband_dob'=>trim(htmlspecialchars($_POST['husband_dob'])),
            'wife_name'=>trim(htmlspecialchars($_POST['wife_name'])),
            'wife_dob'=>trim(htmlspecialchars($_POST['wife_dob'])),
            'residence_state'=>trim(htmlspecialchars($_POST['residence_state_married'])),
            'dependent_spouse'=>trim(htmlspecialchars($_POST['dependent_spouse_married']))
          );
      }
    else{
        if(isset($_SESSION['married']))
   {
             unset($_SESSION['married']);
             unset($_SESSION['facts']);
         }
        $_SESSION['single']=array(
            'single_name'=>trim(htmlspecialchars($_POST['single_name'])),
            'single_dob'=>trim(htmlspecialchars($_POST['single_dob'])),
            'residence_state'=>trim(htmlspecialchars($_POST['residence_state_single'])),
            'dependent_spouse'=>trim(htmlspecialchars($_POST['dependent_spouse_single']))
        );
    }
}

if($_SESSION['married']||$_SESSION['single']['dependent_spouse']=="yes")
{
$countable_equity=0;

}
else{
 if(($_POST['primary_residence']-$csra_max)>0)
  {$countable_equity= $_POST['primary_residence']-$csra_max;}
   else{$countable_equity=$csra_max;}
}

//echo $countable_equity;
 ?>

<script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/autoform.js"></script>
<script type="text/javascript" src="<?php echo get_bloginfo('template_url'); ?>/js/format.20110630-1100.min.js" ></script>

<div class="whitebox">
    <div class="whiteboxtop"></div>
    <form id="commentForm" action="<?php echo get_permalink(339);?>" method="post">

        <?php if(isset($_SESSION['married'])): ?>
            <div class="mainwrapperfin">
                <h3>form 2</h3>
                <table>
                    <tr>
                        <td class="form_text">Residency:</td>
                        <td class="form_input">
                            <input TABINDEX=26 type="text" name="primary_residence" id="primary_residence" onblur="calculate(this.value,'estate'); check_equity(this.value);" size="30" class="required number" value="<?php echo $_SESSION['facts']['primary_residence'];?>"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="form_text">Countable Equity:</td>
                        <td class="form_input">
                            <input TABINDEX=27 type="text" name="countable_equity" id="countable_equity" readonly="readonly" size="30" 
                                   class="required number" value="<?php echo $countable_equity ?>"/>
                        </td>
                    </tr>
                    </table>
                   <input class="nextbutton" type="submit" name="submit" value="Next">
                <a class="nextbutton" href="<?php echo get_permalink(219);?>">Previous</a>
            </div>
        

<!--********************************************* Single starts here *********************************************-->
        
                    <tr>
                        <td class="form_text">Residency:</td>
                        <td class="form_input">
                            <input TABINDEX=19 type="text" name="primary_residence" id="primary_residence" onblur="calculate(this.value,'estate'); check_equity(this.value);" size="30" class="required number" value="<?php echo $_SESSION['facts']['primary_residence'];?>"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="form_text">Countable Equity:</td>
                        <td class="form_input">
                            <input type="hidden" name="dependent_other_spouse" id="dependent_other_spouse" value="<?php echo $_SESSION['single']['single_dependent_spouse']; ?>"/>
                               <input TABINDEX=20 type="text" name="countable_equity" id="countable_equity" readonly="readonly" size="30" class="required number" value="<?php echo $_SESSION['facts']['primary_residence'];?>"/>
                        </td>                                                
                    </tr>
                    
                </table>
                <input TABINDEX=30 class="nextbutton" type="submit" name="submit" value="Next"/>
                <a class="nextbutton" href="<?php echo get_permalink(219);?>">Previous</a>
            </div>
    <?php endif; ?>
    
</form>

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 38854725
storing data of multipage form in a session
I would recommend a slightly different approach.  Cookie the browser so you can have a longer memory of the client (longer than the PHP session).  Update the data base immediately with each data element you receive.  If the client is distracted or has to step away and come back later, the session-only strategy for data storage will cause the web site to "forget" the client input.  That's really annoying, especially if you have a multi-page form, and it's easy to prevent with good design.  

A paradigm you might consider is something like the anonymous shopping cart.  Visit most merchant sites, put something in your cart, but don't check out, just close the browser.  Come back to the site later, and you'll find that your cart is still there, ready and waiting.  That's the right way to handle any multi-page form.
0
 
LVL 1

Assisted Solution

by:shawnlearn
shawnlearn earned 0 total points
ID: 38854756
Thanks Ray for your response. I appreciated your approach and i know this is the best way to do it .but i am running out of time and i invested lot of time in doing it in this way my work is almost complete and this is the only issue to be resolved . Can you please suggest any quick way to do this at this time of moment. I truly believe the way you suggest above is the best way to do it and i will keep in mind in future projects.




Shawn
0
 
LVL 20

Expert Comment

by:Mark Brady
ID: 38854759
I agree Ray.
Php sessions have their place for sure but cookies are the way to go in this case. We have multi-section forms on our work website and the way we do that is each section is recorded as a draft copy of that section and we in fact store each part in the DB with a unique id and name. That way we can have "back" and "forward" buttons so they can navigate their way around the whole signup process.
0
 
LVL 1

Author Closing Comment

by:shawnlearn
ID: 38892624
Thanks experts for helping me . I will use method  suggested by you in future
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38893137
Please see the grading guidelines:
http://www.experts-exchange.com/help/viewHelpPage.jsp?helpPageID=26

What was wrong here?  The last we heard from you was ten days ago.  You didn't ask for anything else, so we had no idea you were dissatisfied with the answer.  Why did you give a bad grade?
0
 
LVL 1

Author Comment

by:shawnlearn
ID: 38895188
Hey Ray, that happened by mistake didn't realize then. Is there a way to redo this? I am happy to do so. And I will take care of grading in future.
0
 
LVL 1

Author Comment

by:shawnlearn
ID: 38895195
You guys are great help and your answers are helping me get better at coding and approach to be taken before I embark on a project. That grade was an honest mistake nothing else, will be careful in future.

Shawn
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38895375
No problem or hard feelings.  I just thought something had gotten lost.

Best regards, ~Ray
0

Featured Post

Turn Insights into Action

Communication across every corner of your business is essential to increase the velocity of your application delivery and support pipeline. Automate, standardize, and contextualize your communication processes with xMatters.

Question has a verified solution.

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

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
When table data gets too large to manage or queries take too long to execute the solution is often to buy bigger hardware or assign more CPUs and memory resources to the machine to solve the problem. However, the best, cheapest and most effective so…
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

691 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