Before you can update, search or delete records from a database, you need to add records to it or have a database that already contains records. The Add Employee template page will be designed to add employees. This page will be redirected automatically to the Master Employee page (e.g., index.php) once the ADD EMPLOYEE button is clicked.
Although, you can use phpMyAdmin (or any other graphical interface app) to insert records into a database table, it is best practice to create a CUSTOM form to insert records which gives you more control over who can access the database and where they can access the database to view, insert, update, or delete records. Also, anybody with the right privilege can access the database from the web.
Since no recordset is needed for the Add Employee page, it is the EASIEST dynamic page to create. However, there is an option at the end of this tutorial on how to convert the static combo box to a dynamic combo box from a database table. However, this does requires a recordset.
The code that will be created will perform the following tasks:
PART A: CREATE STATIC CONTENT
Create Static Form and Form Elements
PART B: ADD DYNAMIC SCRIPTS
Add SQL INSERT Recordset Script
Add Redirect User To Another Page Script
Option 1: Validate Form Elements
Option 2: Populate Menu Dynamically
PART A: CREATE STATIC CONTENT
Create Static Form and Form Elements
Create form and form elements (also known as form variables or form controls) that are needed for the Add Employee Page.
Open the add_employee.php page that you created earlier in the SSI section.
Write (or copy) the following highlighted code below the
<h2>
tag: WHY: To create a form for the ADD EMPLOYEE page. TIP: You can use Dreamweaver or another editor to easily create the form and form elements.
<h2 class="ui-body ui-body-a ui-corner-all">ADD EMPLOYEE</h2>
<form action = "add_employee.php" method="post">
<div class = "ui-body ui-body-a ui-corner-all">
<p><label for = "FirstName">First Name:</label>
<input type="text" name = "FirstName" id="FirstName" data-mini = "true"></p>
<p><label for = "LastName">Last Name:</label>
<input type = "text" name = "LastName" id = "LastName" data-mini = "true"></p>
<p><label for = "City">City:</label>
<input type = "text" name = "City" id="City" data-mini = "true"></p>
<p><label for = "State">State:</label>
<input type = "text" name = "State" id = "State" data-mini = "true"></p>
<p><label for="StartDate">Start Date:</label>
<input type = "date" name = "StartDate" id = "StartDate" data-mini = "true"></p>
<p><label for = "Note">Note:</label>
<textarea cols = "40" rows = "8" name ="Note" id = "Note" data-mini = "true" class = "define-textarea"></textarea></p>
<p><label for = "Department">Department:</label>
<select name = "Department" id = "Department" data-mini = "true" data-inline = "true">
<option>Human Resource</option>
<option>IT</option>
<option>Engineering</option>
<option>Marketing</option>
<option>Manufacturing</option>
<option>Sales</option>
</select></p>
<p><label for = "Image">Image:(e.g., john_doe.jpg)</label>
<input type = "text" name = "Image" size = "20" data-mini = "true"/></p>
<p><input type = "submit" name = "submitted" value = "ADD EMPLOYEE" data-inline = "true"
data-mini = "true" data-icon = "plus" data-iconpos = "left"/></p>
<input type = "hidden" name = "submitted" value = "true" />
</div>
</form>
CODE EXPLANATION:
Each of the form elements MATCHES the column names in the database (except for the button). This is called DATA BINDING where you "bind" form variables in a form to the SAME column names in a database.
Notice there is no spaces in FirstName, LastName and StartDate of the database names because it is best practice not to include spaces in database column names.
Ensure that the button type is set to submit; otherwise, the form will not execute when button is clicked. (e.g., <p><input type="submit" name="submitted" value="ADD EMPLOYEE" data-inline="true" data-mini="true"/></p>).
The Department drop-down list currently has hard-wired values. There is an optional set of steps that can be used at the end of this tutorial that you can use to dynamically populate the Department drop-down box.
The hidden field (<input type="hidden" name="submitted" value="true">) will be used by an "if" statement later to check if the form is submitted.
CHECK POINT: Save the file and preview it in a browser. You should see the form displays when the page loads.
PART B: ADD DYNAMIC SCRIPTS
Add SQL INSERT Recordset Script
Now that we have the form and form elements created, it is time to add the code that will actually ADD the data from the form to a single row in the database. The following code performs the five actions listed below. Comments are optional but are used to explain code. Blank lines are also optional but are used to emphasize specific code blocks.
Check to see if form has been submitted
Set variables for each form elements except submit button or hidden field
Store a reference of SQL statement in a variable
Execute the query
Write the following highlighted code block above the opening
<form>
tag. Comment is optional but are written to explain code. WHY: To create a conditional statement that will check to see if the form has been submitted. Remember, that a form is NOT submitted until AFTER the submit button (e.g., ADD EMPLOYEE) has been pressed. If you want to test this, add print ("Hello, World") between the curly braces and then save the file and press the ADD EMPLOYEE button to see the text. Don't forget to delete this print statement once done.
<?php
// Check to see if form has been submitted
if(isset($_POST["submitted"]))
{
}
?>
<form>
Between the curly braces ( { ... } ) of the if statement, add the following highlighted code: WHY: To set variables for each database bound form elements.
<?php
// Check to see if form has been submitted
if(isset($_POST["submitted"]))
{ // Set variables for each database bound form elements. $FirstName = trim($_POST["FirstName"]); $LastName = trim($_POST["LastName"]); $City = trim($_POST["City"]); $State = trim($_POST["State"]); $StartDate = trim($_POST["StartDate"]); $Note = trim($_POST["Note"]); $Department = $_POST["Department"]; $Image = trim($_POST["Image"]);
}
?>
<form>
CODE EXPLANATION:
The $_POST["form_name"] is a FORM variable that reference the value of the form element id (e.g., id="FirstName"). For example, if a user type his or her first name (e.g., Cornelius) into a input text form element with a attribute id of FirstName, Cornelius would be the value of the form variable $_POST["FirstName"].
The trim ( ) method is OPTIONAL but is used with input fields to trim spaces from users inputs. Notice however, the $Department variable doesn't not need a trim() method because it is not an input field and it get its values from a preset list of values from the combo box created earlier.
Storing the form variable (e.g., $_POST[ ]) in PHP variables are optional. However, they make the code easier to read as will be seen later.
Write the following highlighted code before the closing curly brace or after the $Image variables. Comments are optional: WHY: To store a reference of the SQL statement as a variable.
<?php
// Check to see if form has been submitted
if(isset($_POST["submitted"]))
{ // Set variables for each database bound form elements. $FirstName = trim($_POST["FirstName"]); $LastName = trim($_POST["LastName"]); $City = trim($_POST["City"]); $State = trim($_POST["State"]); $StartDate = trim($_POST["StartDate"]); $Note = trim($_POST["Note"]); $Department = $_POST["Department"]; $Image = trim($_POST["Image"]);
// SQL INSERT QUERY ----------------------------------------------------- // Store a reference of SQL Statement in a variable $query_insertEmployee = "INSERT INTO employees(FirstName,LastName,City,State,StartDate,Note,Department,Image,DateEntered) VALUES('$FirstName','$LastName','$City','$State','$StartDate','$Note','$Department','$Image',NOW())"; }
?>
<form>
CODE EXPLANATION:
Notice that the EmployeeID is NOT included in the list of database column names. That's because it is a primary key that is set to auto increment when a record is created in the database. You could have however included it in the list and set it value to zero (0) which will automatically get updated in the database with the next logical value. However, this is not necessary. Notice also that the complete INSERT statement is WRAPPED in double quotes with each value WRAPPED in single quote.
Notice that double and single quotes are used because they are needed.
While not required, It is common practice to write SQL statements (e.g., INSERT, UPDATE, DELETE, SELECT) in all capital letters to make it easier to identify SQL statements within a lot of code.
When inserting information between the parentheses for both the INSERT INTO and VALUE ensure that:
they have the same number of values
they are in the same order for each column in the database table that they will match.
they are separated by commas
Strings and dates are in quotes
Numbers are not in quotes
You are not limited to form variables, notice that the last element has the built in NOW() method which returns the current date for the DateEntered value. Also, this is NOT a user input field but it still get saved to the database. This is useful when you want to capture the date information was last saved to the database.
Write the following highlighted code before the closing curly brace: WHY: To execute the SQL query and then close the connection to the database.
// Store reference of SQL Statement in a variable $query_insertEmployee =" INSERT INTO employees(FirstName, LastName,City,State,StartDate,Note,Department,Image,DateEntered) VALUES('$FirstName','LastName','$City','$State','$StartDate','$Note','$Department','$Image', NOW())";
// Execute querymysql_query($query_insertEmployee);
// Close connection once query is complete mysql_close();
}
?>
CODE EXPLANATION:
The mysql_query method is used to query (question) the database with the SQL statement that is passed into it. Because most queries are complex, it is best practice to store a reference of the query as a variable and then pass that variable to the mysql_query method.
It is best practice to close a connection once you are done using it. The mysql_close() method is used to close the connection once the INSERT query is completed.
ULTRA GEEK ONLY: Instead of creating individually variables, you could have added dynamic fields directly to the INSERT query. However, it would make the line hard to read and more error proned. Because SQL queries can be complex, it is best to create variables and pass these variables to the mysql_query () method.
CHECKPOINT: Save the file and test the page by entering some data into the text fields and then clicking on the ADD EMPLOYEE button. You can go to the database using phpMyAdmin to ensure a record was added. Later, we will create a page so that you can "see" the changes in real time within an actual page.
Add Redirect User To Another Page
Script
After page is submitted and data added to the database, a user needs to be REDIRECTED to the home page (index.php). You could also create a separate confirmation page if you wanted or needed to.
Write the following highlighted code before the closing curly brace. WHY: To redirect the user to another page.
// Execute query
mysql_query($query_insertEmployee);
// Close connection once query is complete mysql_close();
// Redirect user to another page header("Location: index.php");
}
?>
CODE EXPLANATION:
If PHP detects an error, the redirect code will not be executed.
the header() method is used to redirect the user to another page by passing it a location (e.g., index.php).
CHECKPOINT: Save the file and test the page by adding data to the form and then clicking the ADD EMPLOYEE button. You should be taken to the home page (e.g., index.php). Using phpMyAdmin, you can check the database to ensure a record was added to the database. Later we will update the Employee Master Page to show the newly entered record.
OPTION 1: Validate Form Elements
When you create a form, you should always validate particular form elements to determine if required form elements have been filled out or that the correct format is given (e.g., email address). There are a host of techniques on how to validate form elements. See Validate under the Enhancements tab for details.
OPTION 2: Populate Menu
Dynamically
While the Department drop-down menu was populated MANUALLY, it is best practice to DYNIMICALLY populate a menu if the SAME menu will be used on MULTIPLE pages. This way, if there are any changes (additions or deletions) to the menu, it can be done from one table in the database and all of the pages will reflect the change. See Automation under the Enhancements tab for details.