Page 1 of 1

Forms, validation and standards

Posted: Fri May 15, 2009 12:05 am
by jkwok
Hi,

I'm brand new to PHP. I have experience programming in JSP and Java and having trouble getting similar functionality in PHP which is purely due to my lack of experience. :D

While my issue is very basic I'm sure, I've researched many sites and they all have different approaches and I'm curious to see if there is a standard practice or not.

I have a page with a form on it. I want the user to be able to fill out the form and submit. I'd then like to use PHP code to verify all the fields have been filled out properly. If there are errors, return to the form page with an error list and the form with the values the user submitted so they can correct it. Otherwise, I'd like the data to be saved to my database, but I've already got that part working.

Here is a code snippet of my form thus far. I don't know whether to set the action to the same page the form is located and process if $_POST['submit'] is set, or have it go to another page to process? I'm also assuming I'll have to have a 'value' attribute in each input tag and set it to a $_POST variable if errors are detected?

Code: Select all

 
<form name="newsAdd" method="post" action="">
  <label>Title: <input type="text" name="title"></label><br />
  <label>Article:<br /><textarea name="article" cols="100" rows="20"></textarea></label><br />
  <label>Publish: <input type="checkbox" name="publish"></label><br />
  <input type="submit" value="Save"><input type="reset" value="Reset">
</form>
 
Any help or direction with this would be greatly appreciated.

Thanks,
Jason

Re: Forms, validation and standards

Posted: Fri May 15, 2009 8:07 am
by mattpointblank
You've identified the main benefit to posting the form to the same page - if you set the form field values to their $_POST values, you can show the same form again using the same code if there's an error. This means if you want to add/modify form fields, you don't have to do it on two pages.

When I process forms, I do something like this:

Code: Select all

 
<?php
          session_start(); // start this to store/display the response message for the form
 
        // this creates an array of variables with a custom function
       // called clean() applied to all the $_POST variables, which sanitises the user input.
    $cleanvars = array_map('clean', $_POST);  
 
        // this 'extracts' all of the $cleanvars variables to new variables with $prefix_ at the start,
       // then the name of the form field, eg $prefix_name etc - this is now safe for database usage
    extract($cleanvars, EXTR_PREFIX_ALL, 'prefix');
 
      // now we have our variables, run through them and check them as necessary
     // if any of the variables fail the checks, set a check variable to false, eg:
 
     $hasErrors = false;
     $errormessage = array();
 
     if($prefix_name == "") { // they left a required field blank
          $hasErrors = true;
          $errormessage[] = "Make sure you enter your name";
     }
 
     // after all your checks, do a test on hasErrors:
 
     if($hasErrors) {
          $_SESSION['response'] = $errormessage; // set a session var of the errors
          session_write_close(); // fixes a bug
          header("Location: form.php"); // send them to this page again
          exit(); // stop processing stuff
     } else {
          // the info was fine, so input it to the database, then redirect them to a success page
     }
 
     // then in your form itself, echo out the value of $_SESSION['response'] (if it exists)
     // and make sure the form fields values contain the $_POST data so they don't lose anything
 
This should work - ask away if you're confused.

Matt

Re: Forms, validation and standards

Posted: Fri May 15, 2009 3:55 pm
by jkwok
Hey Mattpointblank,

Your code looks really good, I like how clean everything looks. I'll try this out and let you know of the results.

Thanks!
Jason

Re: Forms, validation and standards

Posted: Mon May 18, 2009 7:05 pm
by jkwok
Hi,

I'm having trouble getting this to work. I'm unsure how the page is supposed to layout. More specifically, does the form go above this code? And is there an if statement I have to set up for the form?

Thanks,
Jason

Re: Forms, validation and standards

Posted: Mon May 18, 2009 7:28 pm
by Christopher
Here are some previous discussions about forms processing:

viewtopic.php?f=19&t=95837

viewtopic.php?f=1&t=80392


Forms processing is not simple to just show a total solution. There are some common support classes that programmers often use for forms in PHP. They may build them or use them from a framework. Do you have any code you can post? We should start there and go through everything you need.

Re: Forms, validation and standards

Posted: Tue May 19, 2009 3:11 am
by mattpointblank
jkwok wrote:Hi,

I'm having trouble getting this to work. I'm unsure how the page is supposed to layout. More specifically, does the form go above this code? And is there an if statement I have to set up for the form?

Thanks,
Jason
The form should go underneath the code above, and when submitted, should submit to itself, eg, the form action attribute should point to the same file the form is saved in. Then, my code above should be wrapped in the following if statement:

Code: Select all

 
if(isset($_POST['submitForm'])) {
     // form processing here
}
 
Then make your your form's submit button is name="submitForm".

Re: Forms, validation and standards

Posted: Wed Jul 15, 2009 11:35 am
by lmg
So far, I have been able to get the form validation part to work; however, as soon as I go to the page which is supposed to write the information into a database, none of my $_POST variables are showing up. Can anyone help me figure out why this is happening?

Form Code:

Code: Select all

<?php 
session_start();
 
    //check how many errors are on the page if the page has been loaded at least a second time
    if($_SESSION['p1_start'] != 1){
        $numErrors=0;
        for($i=0; $i < 20; $i++){
            if(!isset($_POST['group'.$i]))
                $numErrors++;
        }
    }
    if($numErrors==0 && $_SESSION['p1_start']!=1)//when the session variable is 1, the number of errors will be 0
        header('Location: selfAudit1_writeToDatabase.php');
    $title="Self Audit";
    include("header.php");
    
    if($numErrors>0)
        echo "<h5>There are ".$numErrors." errors on this page.</h5><br>";
    
    //connect to the database to get all of the questions for this section. 
    include("dbConnection.php");
 
    $query="SELECT questions FROM question WHERE question_id BETWEEN 0 AND 20";
    $result=mysql_query($query);
    
    mysql_close();
//}
?>
 
 
<style type="text/css">
    DIV.alignment {text-align: justify}
    DIV.boldText {font-weight: bold}
</style>
 
<form method="post" action="#">
 
<a href="session.php">Return to Main Menu</a><br><br>
<br>
<br>
<h3>Section 1: Organization of the Radiation Treatment Program</h3>
<br>
<br>
<br>
 
<table width=100% border=0 cellspacing=10 cellpadding=20>
 
<!-- The following code generates the page content -->
 
<?php
//put all other info on page
for($i=0; $i < mysql_numrows($result); $i++){
    echo "<tr><td>";
    if($_SESSION['p1_start']!=1 && !isset($_POST['group'.$i]))
        echo "<h5>:'(<h5>";
    echo "</td>
    <td width=60%><div class=alignment>".mysql_result($result, $i)."
        <br><br><div class=boldText>
        <INPUT TYPE='radio' NAME='group$i' VALUE='1'". (($_POST['group'.$i]==1) ? "checked='checked'" : "") ."><span title='Non-Compliant. Quality requirement not addressed.'>NC</span>
        &nbsp; &nbsp;
        <INPUT TYPE='radio' NAME='group$i' VALUE='2'". (($_POST['group'.$i]==2) ? "checked='checked'" : "") ."><span title='Minimally Compliant. Quality requirement addressed.'>MC</span>
        &nbsp; &nbsp;
        <INPUT TYPE='radio' NAME='group$i' VALUE='3'". (($_POST['group'.$i]==3) ? "checked='checked'" : "") ."><span title='Partially Compliant. Quality requirement addressed and implemented.'>PC</span>
        &nbsp; &nbsp;
        <INPUT TYPE='radio' NAME='group$i' VALUE='4'". (($_POST['group'.$i]==4) ? "checked='checked'" : "") ."><span title='Substantially Compliant. Quality requirement addressed and implemented. Documentation reflects actual practice.'>SC</span>
        &nbsp; &nbsp;
        <INPUT TYPE='radio' NAME='group$i' VALUE='5'". (($_POST['group'.$i]==5) ? "checked='checked'" : "") ."><span title='Fully Complaint. Quality requirement addressed, implemented, and audited annually for compliance and continuous improvement. Documentation reflects actual practice.'>FC</span>
        &nbsp; &nbsp;
        <INPUT TYPE='radio' NAME='group$i' VALUE='6'". (($_POST['group'.$i]==6) ? "checked='checked'" : "") ."><span title='Not Applicable. Does not apply.'>NA</span><br><br>
        </td>
        
        <td>
        <div class=boldText>Comments:</div><br>
            <TEXTAREA COLS='75' name='comment$i' style='background:#EEE9DF'>".$_POST['comment'.$i]."</TEXTAREA><br><br>
        </td>
    </tr>";
}
 
$_SESSION['p1_start']++;
$_SESSION['p2_start']=1;
 
?>
 
</table>
 
<!--End of survey-->
 
<br>
<input type="submit" name="continue" value="Continue">
<br>
<br>
<br>
 
</form>
 
<?php
    include("footer.html");
?>
Database code:

Code: Select all

 
 
<?php
 
    session_start();
 
    //connect to database
    include("dbConnection.php");
 
    //query the database for all audits for the user. If none are found, audit number is 1. Otherwise, audit
        //number is (largest audit number) + 1.
    //$prequery = "SELECT MAX(auditNumber) FROM auditData WHERE username=$_SESSION[username]";
    $prequery="SELECT COUNT(*) FROM auditData WHERE username='user'";
    $result=mysql_query($prequery);
    $numRows=mysql_result($result,0);
    
    if($numRows==0)
        $auditNumber=1;
    else{
        $prequery1 = "SELECT MAX(auditNumber) FROM auditData WHERE username='user'";
        $result1=mysql_query($prequery1);
        $auditNumber = mysql_result($result, 0) + 1;
    }
    
    //get the date
    $date = date("F j, Y");
 
    //the question id will always be 1 until a new set of questions needs to be made. The answer id will be autoincremented. 
        //Update auditData table.
    $questionID=1;
    //$prequery2 = "INSERT INTO auditData VALUES('$_SESSION[username]', '$auditNumber', '$date', '$questionID', '')";
    $prequery2 = "INSERT INTO auditData VALUES('user', '$auditNumber', '$date', '$questionID', '')";
    mysql_query($prequery2);
 
    //Now, we fill in the answer/comment fields in the answer table.
 
    //get the answer id from our table
    //$prequery3 = "SELECT answerID from auditData WHERE username=$_SESSION[username] AND auditNumber=$auditNumber";
    $prequery3 = "SELECT answerID from auditData WHERE username='user' AND auditNumber=$auditNumber";
    $result = mysql_query($prequery3);
    $answerID = mysql_result($result, 0);
    $_SESSION['answerID']=$answerID;
        
    //create part of the query
    $i=0;
    $partialQuery="('$answerID', ";
    //add answers to the query. If any are empty, an error message will be output requesting the user to go back and answer the empty
        //question.
    while($i < 20){
        echo "iteration$i=".$_POST['group'.$i]."<br>";
        $partialQuery .= "'".$_POST['group'.$i]."', ";
        $i++;
    }
    //add empty spaces for future sections
    while($i < 79){
        $partialQuery .= "'', ";
        $i++;
    }
    //add comments to the query
    $j=0;
    while($j < 19){
        $partialQuery .= "'".$_POST['comment'.$j]."', ";
        $j++;
    }
    //add empty spaces for future comments
    while($j < 78){
        $partialQuery .= "'', ";
        $j++;
    }
    $partialQuery .= "'')";
    //$partialQuery .= "'".$_POST['comment'.$j]."')";
    
    $query = "INSERT INTO answer VALUES".$partialQuery;
    
    echo "query=$query";
    //query the database
    mysql_query($query);
 
    mysql_close();
 
    //header('Location: selfAudit2.php');
//} 
?>
 
Output when page is run:

Code: Select all

iteration0=
iteration1=
iteration2=
iteration3=
iteration4=
iteration5=
iteration6=
iteration7=
iteration8=
iteration9=
iteration10=
iteration11=
iteration12=
iteration13=
iteration14=
iteration15=
iteration16=
iteration17=
iteration18=
iteration19=
query=INSERT INTO answer VALUES('12', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '')

Re: Forms, validation and standards

Posted: Thu Jul 16, 2009 4:00 pm
by lmg
I found a workaround to my problem:

In the if statement on line 12 of the form page, I went through all of the $_POST variables and assigned them to a $_SESSION variable (ie: $_SESSION['group1']=$_POST['group1']) before the header() command.