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. While minimum validation will be done with the required keyword, additional validation can be done with some form elements.
<form action = "" method="POST">
<div class = "ui-body ui-body-a ui-corner-all">
<p><label for = "FirstName">First Name:</label>
<input name = "FirstName" type="text" required="required" id="FirstName"
value="<?php echo $result[0]['FirstName']; ?>" data-mini = "true"></p>
<p><label for = "LastName">Last Name:</label>
<input name = "LastName" type = "text" required="required" id = "LastName"
value="<?php echo $result[0]['LastName']; ?>" data-mini = "true"></p>
<p><label for = "Title">Title:</label>
<input name = "Title" type ="text" required="required" id = "Title"
value="<?php echo $result[0]['FirstName']; ?>" data-mini = "true"></p>
<p><label for = "City">City:</label>
<input name = "City" type = "text" required="required" id="City"
value="<?php echo $result[0]['City']; ?>" data-mini = "true"></p>
<p><label for = "State">State:</label>
<input type = "text" required="required" name = "State" id = "State" data-mini = "true"
value="<?php echo $result[0]['State']; ?>"></p>
<p><label for="StartDate">Start Date:</label>
<input name = "StartDate" type = "date" required="required" id = "StartDate"
value="<?php echo $result[0]['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"><?php echo $result[0]['Note']; ?></textarea></p>
<p><input type = "submit" name = "add_record" value = "SAVE" data-inline = "true"
data-mini = "true" data-icon = "plus" data-iconpos = "left"/></p>
</div>
</form>
CODE EXPLANATION:.
- You may notice the word required used by itself in some books. To be HTML5 valid, attribute VALUES need to be in single or double quotes. While required = "required" is not nice looking, it makes the code HTML 5 valid.
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 changes.
<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>
<?php
/* Retrieve data from Department column for combo box */
$pdo_statement = $pdo_conn->prepare( "SELECT DepartmentID, Dept FROM departments" );
$pdo_statement->execute();
$result = $pdo_statement->fetchAll();
?>
<!doctype html>
<p><label for = "Department">Department:</label>
<select name="Department" id="Department" data-mini="true" data-inline="true"> <!-- Loop through middle of select tag ----------------------------------------- --> <?php
foreach ( $result as $row ) {
?> <option><?php echo $row['Dept']; ?></option> <?php
}
?>
<!-- End of select ------------------------------------------------------------------------- --> </select></p>
CAUTION: Pay attention to the added comma:
- Before the two words Department
- After the NOTE statement
<?php require("db.php");
if(!empty($_POST["add_record"])) {
$sql = "INSERT INTO employees (FirstName, LastName, Title, City, State, StartDate, Note, Department)
VALUES (:FirstName, :LastName, :City, :Title, :State, :StartDate, :Note, :Department)";
$pdo_statement = $pdo_conn->prepare( $sql );
$result = $pdo_statement->execute( array(
':FirstName'=>$_POST['FirstName'],
':LastName'=>$_POST['LastName'],
':Title'=>$_POST['Title'],
':City'=>$_POST['City'],
':State'=>$_POST['State'],
':StartDate'=>$_POST['StartDate'],
':Note'=>$_POST['Note'],
':Department'=>$_POST['Department']
) ); if (!empty($result) ){ header('location:master_page.php');
}
}
?>
While having images already in an folder name images is convenient, it is not best practice. In this case, you would have to FTP images to the this folder separate and remember the names to enter into the ADD EMPLOYEE form page. This is not very practical. To be a true CMS, an image should be uploaded AUTOMATICAILLY to the server when a record is added to the database. To do this requires some specialize handling of binary data in the form.
To make an EXISTING form capable of uploading a file (e.g., image, etc.) requires:
<!-- End of select -------------------------------------------------------------- -->
</select></p>
<p><label for = "Image">Image:(e.g., john_doe.jpg)</label>
<input type = "text" name = "Image" size = "50" data-mini = "true"/></p>
CAUTION: Pay attention to the added commas:
- Before the first two Image words - At the end of ['Department']
<?php require("db.php");
if(!empty($_POST["add_record"])) {
$sql = "INSERT INTO employees (FirstName, LastName, Title, City, State, StartDate, Note, Department, Image)
VALUES (:FirstName, :LastName, :City, :Title, :State, :StartDate, :Note, :Department, :Image)";
$pdo_statement = $pdo_conn->prepare( $sql );
$result = $pdo_statement->execute( array(
':FirstName'=>$_POST['FirstName'],
':LastName'=>$_POST['LastName'],
':Title'=>$_POST['Title'],
':City'=>$_POST['City'],
':State'=>$_POST['State'],
':StartDate'=>$_POST['StartDate'],
':Note'=>$_POST['Note'],
':Department'=>$_POST['Department'],
' :Image'=>$_POST['Image']
) ); if (!empty($result) ){ header('location:master_page.php');
}
}
?>
Before you attempt to create an upload functionality, you need to ensure that your server is setup to do uploads
file_uploads = On
<form action = "" method="POST" enctype="multipart/form-data" data-ajax="false">
CODE EXPLANATION:
- The form element must be edited to have an enctype="multipart/form-data" and method="post" attribute if it does
not already have either of these attributes. Without these requirements, the file upload will not work.
- The enctype attribute lets the browser know that "multiple" data type can be submitted (e.g., text and binary).
- The method attribute is how to file is submitted--in this case post.
- The data-ajax attribute has to be set to false when using jQueryMobile. Otherwise, the upload function will not work.
<p><label for = "Image">Image:(e.g., john_doe.jpg)</label>TO:
<input type = "text" name = "Image" size = "50" data-mini = "true"/></p>
<p><input type = "file" name = "fileToUpload" id="fileToUpload" size = "20" data-mini = "true"/>
<label for = "Image">Image:(e.g., john_doe.jpg)</label>
<input name = "Image" type = "text" size = "50" data-mini = "true" placeholder = "Enter same name from Upload dialog box here"
maxlength = "50" required = "required" /></p>
CODE EXPLANATION:
- This is used to create a text field AND a browser button so that a user can either type in a file name or browser
to a file on their computer.
- Notice that there is both the type of "text" and "file." The "file" type cannot be used in the SQL query so the "text"
type is still needed. Later, we will add a value attribute to the "text" type and make its value the same as the image
name (e.g., value = "ann_ricoh.jpg) based on a dynamic variable created by the uploadScript.php script so that it CAN
be used. We will also hide this field.
if (!empty($result) ){
// header('location:master_page.php');
}
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>TO:
<!-- <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> -->
</form>
<pre>
<?php
if (isset($_POST['add_record'])) { print_r($_FILES)
}
?>
</pre>
</form><pre> <?php
if (isset($_POST['add_record'])) { print_r($_FILES)
} ----------------------
?> --------------------
</pre> -------------
CAUTION: Be careful NOT to include a "d" on the end of require (e.g., required).
<?php require 'uploadScript.php';?>
<?php
CODE EXPLANATION:
- The require statement is used to insert the content of another PHP file into PHP file before the server execute it. There
is also an include statement that could be used. The different is:
- require will produce a fatal error (E_COMPILE_ERROR) and stop the script
- include will only produce a warning (E_WARNING) and the script will continue
- In the case of a CMS, it is always wise to use the require statement to avoid compromising the app security.
The include is used if you would like to create a standard header, content, footer, or menu files for all your web pages.
Then, when one of these areas need to be updated, only that PHP script file need to be updated.
IMPORTANT INFORMATION: The steps below is for information use only to show how the uploadScript.php file was create.
You DO NOT have to do them unless you want to create the script yourself.
<?php
echo "Hello World";
?>
You want to safeguard that an actual image is being upload to the server.
<?php // Set variables upfront ----------------------------------------------
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image ---------------------
if(isset($_POST["add_record"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
} // End of complete upload script ----------------------------------------- ?>
CODE EXPLANATION:
- $target_dir = "images/" specifies the directory where the file is going to be uploaded.
It is important to add the forward slash (/) at the end.
- $target_file specifies the file name to be uploaded.
- $uploadOk=1 is used to set a flag that will be used later.
- $imageFileType holds the file extension (e.g., jpg, png, gif, txt).
- The outer "if" statement checks to see if the ADD EMPLOYEE button has been clicked. - The inner "if/else" statement is used to check if the image is an actual image and then set the flag.
You should limit the file size that a user can upload by checking the file for a certain size. In our case, if the file size is larger than 500KB, a message is displayed and $uploadOk is set to 0:
// Check file size ------------------------------------------------------
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "File is too large.";
$uploadOk = 0;
}
} // End of complete upload script
?>
CODE EXPLANATION:
- The "if" statement checks if the fileToUpload size is greater than 500KB. If so, display a message and set the $uploadOK flag to zero.
- The fileToUpload is the value of the name attribute of the file input field.
(e.g., <input type = "file" name = "fileToUpload" id="fileToUpload" size = "20" data-mini = "true"/>).
Since the only thing we want a user to upload is an image, we can also check to ensure that only the required image format is uploaded.
// Allow only certain image formats -------------------------------------------------------------------------
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
{
echo "Only jpg, jpeg, png, or gif image formats are allowed.";
$uploadOk = 0;
} } // End of complete upload script
?>
CODE EXPLANATION:
- The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an error message before setting $uploadOk to 0:
Now, it's time to write the code that will ACTUALLY UPLOAD the file is there is no errors.
// Check if $uploadOk is set to 0 by the error flag ------------------
if ($uploadOk == 0)
{
echo "File was not uploaded.";
// If everything is OK, attempt to upload file
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else
{
echo "There was an error uploading file.";
}
}
} // End of complete upload script
?>
<p> <input type = "file" name = "fileToUpload" id="fileToUpload" size = "20" data-mini = "true"/>
<label for = "Image">Image:(e.g., john_doe.jpg)</label>
<input name = "Image" type = "text" required placeholder ="Enter same name from Upload dialog
box here" size = "50" maxlength="50" data-mini = "true" value="<?php echo $selectedFile ?>"/></p>
// Set variables upfront ----------------------------------------------
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$selectedFile = $_FILES["fileToUpload"]["name"];
You should always check if the file already exists in the uploads folder.
CAUTION: Be careful to NOT place code ABOVE the curly brace and comment statement
(e.g., } // End of complete upload script) and what do with the other code block.
// Check if file already exists --------------------------------------
if (file_exists($target_file)) {
echo "Image already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by the error flag ------------------
if ($uploadOk == 0)
CODE EXPLANATION:
- The file_exists() method is used to check if the $target_file exists. If it does, display a message and change the $uploadOK flag to zero.
<!-- <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> -->TO:
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
if (!empty($result) ){TO:
// header('location:master_page.php');
}
if (!empty($result) ){
header('location:master_page.php');
}
<input name = "Image" type = "text" required placeholder ="Enter same name from Upload dialog box here"
size = "50" maxlength="50" data-mini = "true" value="<?php echo $selectedFile ?>"/>
<input name = "Image" type = "hidden" required placeholder ="Enter same name from Upload dialog box here"
size = "50" maxlength="50" data-mini = "true" value="<?php echo $selectedFile ?>"/>
Below is the complete PHP upload code block.
<?php
// Check if ADD EMPLOYEE button has been click -------------------------
if ( isset( $_POST[ "add_record" ] ) ) {
// Set variables upfront ----------------------------------------------
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image ------------------------------
$check = getimagesize( $_FILES[ "fileToUpload" ][ "tmp_name" ] );
if ( $check !== false )
{
echo "File is an image - " . $check[ "mime" ] . ".";
$uploadOk = 1;
}
else
{
echo "File is not an image.";
$uploadOk = 0;
}
// Check file size ------------------------------------------------------
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "File is too large.";
$uploadOk = 0;
}
// Allow only certain image formats -------------------------------------------------------------------------
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif")
{
echo "Only jpg, jpeg, png, or gif image formats are allowed.";
$uploadOk = 0;
}
// Check if file already exists --------------------------------------
if (file_exists($target_file)) {
echo "Image already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by the error flag ------------------
if ($uploadOk == 0)
{
echo "File was not uploaded.";
// If everything is OK, attempt to upload file
}
else
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
else
{
echo "There was an error uploading file.";
}
}
} // End of complete upload script
?>