Php-mysql Course

Usualy, after the user fills the form and submit it, the page is reloaded and the form is empty. In case of an error, the user need to write again all those data to submit the form.
It is user-friendly if we keep the data that the user has added in form fields before submitting it, he will correct /write only data in the fields with errors.


Here's an example with a form with various type of fields, defined in a PHP file.
If there are erros in the fields filled in, it keeps the data already added in form and displays the error(s) and the form, else it displays a confirmation message.
<?php
// array with values for each form field, most empty
$fval = array('fname'=>'', 'femail'=>'', 'fgen'=>'', 'fgenm'=>'male', 'fgenf'=>'female', 'ffood'=>'', 'fmess'=>'');

// a variable for errors, initially empty
$ferror = '';

// if there is data submited from form,
if(isset($_POST['fsubmit'])) {
  $fval = array_replace($fval, $_POST);      // add $_POST data in $fval to replace the initial values

  // validate the fields and add the errors in $ferror variable
  if(strlen($_POST['fname'])<3) $ferror .= '- The Name must contains at least 3 characters <br/>';
  if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_POST['femail'])) {
    $ferror .= '- Add a valid e-mail address <br/>';
  }
  if(!isset($_POST['fgen'])) $ferror .= '- Select a Gender <br/>';
  if($_POST['ffood']=='--' or $_POST['ffood']=='') $ferror .= '- Select a Food preference <br/>';

  // if there is no errors ($ferror is empty) sets a $confirm
  if($ferror==='') $confirm = '<h3>The data was successfully added</h3>';
}

          /* Now define the Form */

// array with values for Select dropdown list
$select_food = array('fruits', 'vegetables', 'cereals', 'dairy', 'cakes');

// sets the <option> tags for Select list
$ffood = '<option>--</option>';
for($i=0; $i<count($select_food); $i++) {
  // sets selected attribute
  $selattr = ($select_food[$i]==$fval['ffood']) ? ' selected="selected"' : '';

  $ffood .= '<option value="'. $select_food[$i]. '"'. $selattr. '>'. $select_food[$i]. '</option>';
}

// define the checked attribute for radio buttons, according to the value of 'fgen'
$fgenm_check = ($fval['fgen']==$fval['fgenm']) ? ' checked="checked"' : '';
$fgenf_check = ($fval['fgen']==$fval['fgenf']) ? ' checked="checked"' : '';

// sets a variable with the HTML code for form
$form = '<form action="" method="post">
 Name: <input type="text" name="fname" id="fname" value="'. $fval['fname']. '" /><br/>
 E-mail: <input type="text" name="femail" id="femail" value="'. $fval['femail']. '" /><br/>
 Gender: <input type="radio" name="fgen" id="fgenm" value="'. $fval['fgenm']. '"'. $fgenm_check. ' />Male
 <input type="radio" name="fgen" id="fgenf" value="'. $fval['fgenf']. '"'. $fgenf_check. ' />Female<br/>
 Food preference: <select id="ffood" name="ffood">'. $ffood. '</select><br/>
 Message (<i>optional</i>):<br/>
 <textarea name="fmess" id="fmess" rows="5", cols="30">'. $fval['fmess']. '</textarea><br/>
 <input type="submit" name="fsubmit" id="fsubmit" value="Submit" /><br/>
</form>';

// if $confirm is set, display it, else, display $ferror and $form
if(isset($confirm)) echo $confirm;
else echo '<div style="color:red;">'. $ferror. '</div><br/>'. $form;
?>
- Test yourself this example, by adding the code above in a php file.

First we set an Array ($fval) with initial values for each form field (with its name for the key), and another variable for errors ($ferror). Then we check if there is data received from form, and validate these data.
In case of errors, we store them in the variable for errors and add the data received through POST in the array for form vield values, to replace the initial values.
Then we display the errors and the form, adding the values that have been filled in.

- To keep the radio button or checkboxes selected, we set a variable with the "checked" attribute for the selected button.
- If the form contains a select drop down list, a good method is to store the option values into an Array, then we traverse the elements of that array and check which option was selected, to add a "selected" attribute.
When the HTML code for the form is created, we add in each field the value stored in the $fval array (this will be the initial values, for the first display, or the value received through POST when data is submited).

A more simple method to keep the values in form fields after submit, it's the following, presented in this example (if you have a simple form with text fields and textarea):
 <?php
// define variables with the value for each field
// the value from POST, if this exist, or an empty value
$name = isset($_POST['name']) ? $_POST['name'] : '';
$email = isset($_POST['email']) ? $_POST['email'] : '';
$msg = isset($_POST['msg']) ? $_POST['msg'] : '';

// define the form into a variable
$fhtml = '<form action="" method="post">
 Name: <input type="text" name="name" value="'. $name. '" /><br/>
 Email: <input type="text" name="email" value="'. $email. '" /><br/>
 Message:<br/>
 <textarea cols="5" rows="35" name="msg">'. $msg. '</textarea><br/>
 <input type="submit" value="Send" />
</form>';

echo $fhtml;         // output /display the form
?>
 

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag is used to add lists into <ul> and <ol> elements?
<dt> <dd> <li>
<ul>
 <li>http://coursesweb.net/html/</li>
 <li>http://coursesweb.net/css/</li>
</ul>
Which value of the "display" property creates a block box for the content and ads a bullet marker?
block list-item inline-block
.some_class {
  display: list-item;
}
Which instruction converts a JavaScript object into a JSON string.
JSON.parse() JSON.stringify eval()
var obj = {
 "courses": ["php", "javascript", "ajax"]
};
var jsonstr = JSON.stringify(obj);
alert(jsonstr);    // {"courses":["php","javascript","ajax"]}
Indicate the PHP class used to work with HTML and XML content in PHP.
stdClass PDO DOMDocument
$strhtml = '<body><div id="dv1">CoursesWeb.net</div></body>';
$dochtml = new DOMDocument();
$dochtml->loadHTML($strhtml);
$elm = $dochtml->getElementById("dv1");
echo $elm->nodeValue;    // CoursesWeb.net
Keep data in form fields after submitting the form

Last accessed pages

  1. Fotorama Image Gallery (6286)
  2. Shape Tween - Flash Animation (6149)
  3. The Mastery of Love (7440)
  4. Get Mime Type of file or string content in PHP (6230)
  5. Countdown Timer with starting time added into a form (11533)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (477)
  2. CSS cursor property - Custom Cursors (81)
  3. The Mastery of Love (72)
  4. PHP-MySQL free course, online tutorials PHP MySQL code (64)
  5. CSS3 2D transforms (46)