Solve business application needs, jazz up existing applications, create user interfaces, or make applications easily accessible for remote users.
Many languages can be used for server-side programming, including Java, JSP, .NET, and PHP. PHP, which stands for PHP: Hypertext Preprocessor, is a scripting language embedded within HTML. Much of PHP's syntax is extracted from C, Java, and Perl, with some unique PHP-specific features. The goal of the language is to allow Web developers to write dynamically generated pages quickly. While PHP is mainly used for server-side scripting, it can also be used from a command-line interface or in standalone GUI applications. In this article, which is an excerpt from HTML for the Business Developer, the focus is on server-side scripting with the business application developer in mind.
PHP can be used for processing input data, generating dynamic page content, and updating server-stored data. One of the most significant features of PHP is its support for a wide range of databases. Writing a dynamic Web application that is able to retrieve and store data is very easy to do with PHP. Currently, PHP supports the databases listed in the table below.
PHP-Supported Databases |
|||
Adabas D |
dBase |
Direct MS-SQL |
Empress |
FilePro (read-only) |
FrontBase |
Hyperwave |
IBM DB2 |
Informix |
Ingres |
Interbase |
mSQL |
MySQL |
ODBC |
Oracle (OCI7 OCI8) |
Ovrimos |
PostgreSQL |
SQLite |
Solid |
Sybase |
Velocis |
Unix dbm |
|
|
In addition to the databases listed, PHP can use a PDO extension, allowing use of any database supported by the PDO extension.
PHP may be used to solve business application needs, jazz up existing applications, create user interfaces, or make applications easily accessible for remote users without requiring additional software or hardware.
Working with Data
Web business applications often need to retrieve data from and store data in a database table or file on the server. PHP can be used for these tasks.
MySQL is used for the examples in this article. In the examples that follow, you will learn how to connect to a MySQL database and input and output data. Some knowledge of SQL is helpful to better understand these examples, but it is not required. These examples could easily be used to access other databases by making slight changes. Additional examples can be found on the http://www.php.net/ Web site.
The code in Figure 1 connects to MySQL server and retrieves data from the master work schedule database, in a table named "workschedule." The retrieved data is displayed on a Web page.
<html>
<head>
<img src="images/bbqbarn.JPG">
<br>
Welcome to Bills Barbeque Barn Master Work Schedule Page!
<br>
Shift Date Shift Start Time End Time
<body>
<?php
// PHP10101 - Working with Data Example
// Connect to data source
mysql_connect("localhost", "userid", "password") or die(mysql_error());
// Select database
mysql_select_db("BillsBarbequeBarn") or die(mysql_error());
// Retrieve data
$data = mysql_query("SELECT * FROM workschedule")
or die(mysql_error());
// Display data in a table
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<td>".$info['ShiftDate'] . "</td> ";
Print "<td>".$info['Shift'] . " </td>";
Print "<td>".$info['StartTime'] . " </td>";
Print "<td>".$info['EndTime'] . " </td></tr>";
}
Print "</table>";
?>
</body>
</head>
</html>
Figure 1: Retrieving data from a MySQL database.
There's not much code here, but it produces big results, as shown in Figure 2. It's really that simple.
Figure 2: Data retrieved from a MySQL database. (Click images to enlarge.)
In this example, we are connecting to a MySQL database, so the connection type is mysql_connect:
// Connect to data source
mysql_connect("localhost", "userid", "password") or die(mysql_error());
The connection has three parameters: the connection, the user ID, and the password. The connection is the DNS where the data resides. In this example, localhost is the location, but it could be a DNS server name or an IP address. The user ID and password parameters are the IDs required to connect to the MySQL database. This statement also uses the die() function to end the script if a connection cannot be made.
The MySQL database name is "BillsBarbequeBarn":
// Select database
mysql_select_db("BillsBarbequeBarn") or die(mysql_error());
The die() function is used again, this time to end the script if the database is not found. Next, the data is retrieved:
// Retrieve data
$data = mysql_query("SELECT * FROM workschedule")
or die(mysql_error());
All fields and records are selected from the table "workschedule" and are stored in a variable named $data.
The data is accessed using the mysql_fetch_array statement. The data is put into the variable $info. The While statement continues to fetch data until no more exists. Finally, the contents are printed, listing the fields ShiftDate, Shift, StartTime, and EndTime to be displayed in an HTML table:
// Display data in a table
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<td>".$info['ShiftDate'] . "</td> ";
Print "<td>".$info['Shift'] . " </td>";
Print "<td>".$info['StartTime'] . " </td>";
Print "<td>".$info['EndTime'] . " </td></tr>";
}
Print "</table>";
The example in Figure 3 adds a few more pieces to further show how data can be used within an application. This example begins with a form prompting the user to enter a first name and last name, as shown in Figure 4. When a valid name is entered and the Submit button is clicked, a work schedule for the employee is retrieved from a database and displayed. This application uses the same database and table as the previous one.
HTML Document PHP10107.html:
<html>
<head>
<!-- PHP10107.html Employee Schedule Inquiry example -->
Welcome to Bills Barbeque Barn Employee Page!
<br>
Please enter your first and last name and press submit to view your schedule.
<form action="PHP10107.php" method="get">
First Name: <input type="text" name="first_name" />
Last Name: <input type="text" name="last_name" />
<br>
<input type="submit" />
</form>
</head>
</html>
PHP Document PHP10107.php:
<html>
<head>
<img src="images/bbqbarn.JPG">
<br>
Bills Barbeque Barn Employee Work Schedule Page!
<br>
<body>
<?php
if (! preg_match( "/^[A-Za-z]+$/", trim($_GET["first_name"]) ))
{
echo ("Please enter your first name." . "<br>");
die;
}
elseif (! preg_match( "/^[A-Za-z]+$/", trim($_GET["last_name"]) ))
{
echo ("Please enter your last name." . "<br>");
die;
}
else
echo ($_GET["first_name"] . " " . $_GET["last_name"] . "'s Work Schedule." . "<br>");
?>
<?php
// Connect to data source
$lname="'" . $_GET["last_name"] . "'";
$fname="'" . $_GET["first_name"] . "'";
mysql_connect("localhost", "userid", "password") or die(mysql_error());
// Select database
mysql_select_db("BillsBarbequeBarn") or die(mysql_error());
// Retrieve data
$data = mysql_query("SELECT * FROM EmployeeSchedule WHERE LastName=$lname and FirstName=$fname order by ShiftDate")
or die(mysql_error());
// Display data in a table
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<td>".$info['ShiftDate'] . "</td> ";
Print "<td>".$info['Shift'] . " </td>";
Print "<td>".$info['StartTime'] . " </td>";
Print "<td>".$info['EndTime'] . " </td>";
Print "<td>".$info['EmployeeNumber'] . " </td>";
Print "<td>".$info['FirstName'] . " </td>";
Print "<td>".$info['LastName'] . " </td></tr>";
}
Print "</table>";
?>
</body>
</head>
</html>
Figure 3: Creating an application to retrieve an employee's work schedule from a database.
Figure 4: The HTML form created by PHP10107.html.
The user is prompted for a first and last name using the form in file PHP10107.html. When the user clicks Submit, PHP10107.php is initiated. The code starts by validating the name entered. If the name is valid, the connection is made and data is retrieved using SQL. To format the SQL statement, the first and last name entered by the user are used for selection. The example first retrieves the fields using $_GET and then formats the names within single quotes to follow correct syntax for the SQL statement:
$lname="'" . $_GET["last_name"] . "'";
$fname="'" . $_GET["first_name"] . "'";
With "Joe" entered for the first name and "Walsh" for the last name, the SQL statement would look like this:
SELECT * FROM EmployeeSchedule WHERE LastName='Walsh' and FirstName='Joe' order by ShiftDate"
The SQL statement selects all records from the "EmployeeSchedule" table where the last name is "Walsh" and the first name is "Joe" and sorts the data in shift-date order:
// Retrieve data
$data = mysql_query("SELECT * FROM EmployeeSchedule WHERE LastName=$lname and FirstName=$fname order by ShiftDate")
The $lname and $fname variables allow for passing the selection information using the user form displayed in PHP10107.html. These variables also format the selection criteria within single quotes to accommodate appropriate statement syntax.
Figure 5 shows the schedule displayed for Joe Walsh, with the date, shift, start, and end times; employee number; first name; and last name. This technique works just as well with many other business inquiries.
Figure 5: The results of the employee work schedule inquiry.
A dynamic application may require a database table to be updated. We will use a customer-service feedback application to show how this can be done. The code in Figure 6 prompts the user to enter feedback information in a form, validates the data, and updates the customer service database. The example is simple, but it provides the techniques to complete the very important task of updating and storing data. The same method might be used to place online orders or update other data.
HTML file - PHP10113.html:
<html>
<head>
<!** PHP10113 Customer service feedback form example **>
Bills Barbeque Barn Customer Service Feedback Page
<br>
<form method="post" action="PHP10113.php">
Email: <input name="email" type="text" /><br />
First Name: <input name="firstname" type="text" /><br />
Last Name: <input name="lastname" type="text" /><br />
Phone Number: <input name="phonenumber" type="text" /><br />
Follow Up (Yes or No): <input name="followup" type="text" /><br />
Customer Service Message:<br />
<textarea name="message" rows="5" cols="40">
</textarea>
<br />
<input type="submit" />
</form>
</head>
</html>
PHP file - PHP10113.php:
<html>
<head>
<img src="images/bbqbarn.JPG">
<br>
Bills Barbeque Barn Customer Feedback Page!
<br>
<body>
<?php
$email_address = '/^[^@s]+@([-a-z0-9]+.)+[a-z]{2,}$/i';
$message=$_POST["message"];
$phonenumber=$_POST["phonenumber"];
$followup=$_POST["followup"]
if (!preg_match($email_address, trim($_POST["email"])))
{
echo "Email address entered is invalid.";
die;
}
elseif (! preg_match( "/^[A-Za-z]+$/", trim($_POST["firstname"]) ))
{
echo ("Please enter your first name." . "<br>");
die;
}
elseif (! preg_match( "/^[A-Za-z]+$/", trim($_POST["lastname"]) ))
{
echo ("Please enter your last name." . "<br>");
die;
}
elseif (strlen($phonenumber)<1)
{
echo ("Please enter your phone number." . "<br>");
die;
}
elseif (trim($_POST["phonenumber"] = " " ))
{
echo ("Please enter your phone number." . "<br>");
die;
}
elseif ($followup !== 'Yes' and $followup !== 'No')
{
echo ("Please enter Yes or No for Follow Up." . "<br>");
die;
}
elseif (strlen($message)<1)
//if (strlen($username)<1)
{
echo ("Please enter your message." . "<br>");
die;
}
?>
<?php
// Format Fields
$email="'" . $_POST["email"] . "'";
$lname="'" . $_POST["lastname"] . "'";
$fname="'" . $_POST["firstname"] . "'";
$phonenumber="'" . $_POST["phonenumber"] . "'";
$message="'" . $_POST["message"] . "'";
$followup="'" . $_POST["followup"] . "'";
// Connect to data source
mysql_connect("localhost", "userid", "password") or die(mysql_error());
// Select database
mysql_select_db("BillsBarbequeBarn") or die(mysql_error());
// Add data
$data = mysql_query("INSERT INTO CustomerService (DateReceived, TimeReceived, EmailAddress, FirstName, LastName, PhoneNumber, Message, FollowUp, Status) VALUES(CURDATE(), CURTIME(), $email, $fname, $lname, $phonenumber, $message, $followup, 'Open')")
or die(mysql_error());
echo "<br>";
echo "Your Customer Service Message has been sent!"
?>
</body>
</head>
</html>
Figure 6: Updating a customer service database.
The code in PHP10113.html displays the customer service form in Figure 7. Once data is entered in the form and the Submit button is clicked, the PHP10113.php document is initiated. The data is retrieved using $_POST and then validated. If the data is valid, the MySQL connection is made and the database table is updated, using the MySQL INSERT INTO syntax. The fields to be updated are listed, and the values are populated using the data retrieved from the form.
Bills Barbeque Barn Customer Service Feedback Page
Email:
First Name:
Last Name:
Phone Number:
Follow Up (Yes or No):
Customer Service Message:
Bottom of Form
Figure 7: The customer service feedback form.
Note in Figure 6 that the status is defaulted to the value Open, the date received is defaulted to the current date, and the time received is defaulted to the current time. Once the update is complete, the message in Figure 8 is displayed, letting the user know the data has been sent.
Figure 8: Letting the user know the result of the data update.
PHP may also be used to work with a text file. The file must first be opened using the fopen() function. The function uses two parameters. The first is for the file name, and the second is for the mode. The example in Figure 9 opens the file in read-only mode. The following table lists valid modes that can be used with fopen().
Valid Modes for fopen() |
|
Mode |
Description |
r |
Read only: Starts at the beginning of the file |
r+ |
Read/Write: Starts at the beginning of the file |
w |
Write Only: Opens and clears the contents of the file or creates a new file if the file referenced does not exist |
w+ |
Read/Write: Opens and clears the contents of the file or creates a new file if the filed referenced does not exist |
a |
Append: Opens and writes to the end of the file or creates a new file if the file referenced does not exist |
a+ |
Read/Append: Preserves file content and writes to the end of the file |
x |
Write Only: Creates a new file and returns False and an error if the file already exists |
x+ |
Read/Write: Creates a new file and returns False and an error if the file already exists |
$file=fopen("PHP10119.txt","r");
Figure 9: The file open function.
The example in Figure 10 reads the text file PHP10119.txt to display the offers from Bills Barbeque Barn for the month of July. The text file is read and displayed using the fopen() and fclose() functions. To access a file, it must be opened. It is also important to close the file.
The While loop uses the end-of-file function, feof(), to read through the file line by line and display the contents using echo. The loop will complete when the end of the file is reached, and the contents of the text file will be displayed to the screen, as shown in Figure 11.
Text File - PHP10119.txt:
Bills Barbeque Barn July Special Offers!
************************************************
10% off all merchandise ordered online
reference offer bbqonline0707
************************************************
20% your entire food bill on your next visit to
Bills Barbeque Barn
reference offer bbqonsite0707
************************************************
Offers valid July 1, 2007 through July 31, 2007
PHP File - PHP10119.php:
<html>
<head>
<img src="images/bbqbarn.JPG">
<br>
Bills Barbeque Barn Special Offers Page!
<br>
<body>
<?php
// PHP10119 - Read and display text file example
$file = fopen("PHP10119.txt", "r") or exit("Unable to open file!");
// Display the file line until the end of the file is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
</body>
</head>
</html>
Figure 10: The code to read and display a text file.
Figure 11: Displaying a text file on a Web page.
The list of monthly specials for Bills Barbeque Barn is a good example of this kind of application. The promotions can be easily changed by replacing the contents of the text document, without having to make changes to the Web site application. This same technique could be used for product-specific information, employee procedures, or order comments.
Although the examples in this chapter use MySQL, connections to other databases can also be used. Figures 12 through 14 show examples of a few other database connections.
<?php
$db_host = "server.mynetwork";
$db_user = "dbuser";
$db_pass = "dbpass";
odbc_connect($db_host, $db_user, $db_pass, "SQL_CUR_USE_ODBC");
@odbc_setoption($this->db_connectid, 1, SQL_ATTR_COMMIT, SQL_TXN_NO_COMMIT)
or die('Failed setoption: ' . odbc_error() . ":" . odbc_errormsg());
@odbc_setoption($this->db_connectid, 1, SQL_ATTR_DBC_DEFAULT_LIB, $this->dbname)
or die('Failed select: ' . odbc_error() . ":" . odbc_errormsg());
?>
Figure 12: Making an ODBC connection.
<?php
$database = 'SAMPLE';
$user = 'db2inst1';
$password = 'ibmdb2';
db2_connect($database, $user, $password);
?>
Figure 13: Making a DB2 connection.
INSERT INTO table VALUES(val1, val2, ... valn);
//MySQL Insert Statement
INSERT INTO table VALUES(val1, val2, ... valn);
INSERT INTO schema.table VALUES(val1, val2, ... valn);
//DB2 Insert Statements
Figure 14: Using a DB2 table reference.
But Wait, There's More!
This article has covered a lot of ground but has barely scratched the surface of the capability and functionality of PHP. PHP can be used for advanced validation, XML processing, FTP, file uploads, and much more.
It is obvious that PHP can bring dynamic capability to a business Web application. If your goal is to get to the Web fast, consider PHP. Its user base continues to grow, and the language continues to evolve, thanks to the efforts of the PHP community.
LATEST COMMENTS
MC Press Online