21
Sat, Dec
3 New Articles

PHP: Server-Side Scripting for the Business Developer

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

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 &nbsp; &nbsp; &nbsp; Shift &nbsp; 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.

090708UbelhorFigure2.jpg

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.

 

090708UbelhorFigure4.jpg

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.

 

090708UbelhorFigure5.jpg

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.

 

090708UbelhorFigure8.jpg

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.

 

090708UbelhorFigure11.jpg

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.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: