Web Design:
|
|
|
|
|
Richard H. Nilsson, July 10, 2003 (Updated for PHP 5, Feburary, 2006) Why PHP?PHP, created by Rasmus Lerdorf in 1959 is now an open source server-side scripting language similar in syntax and grammer to JavaScript, but with many strong advantages over its client-side predecessor. PHP is a recursive acronym for "PHP: Hypertext Preprocessor". Like JavaScript, PHP is free, in the sense that all you have to do is host your site with an ISP that provides it. PHP and MySQL, a powerful enterprise-class database server application, are both provided free on some hosting services with even their basic services in the $20/month range. If MySQL is a bank, PHP is your ATM, enabling you to save and withdraw resources. I prefer the combination of Linux OS, Apache Web server, MySQL and PHP for my hosting choice, commonly referred to as "LAMP" technology. Unlike JavaScript, PHP code is invisible to the browser. Before sending your browser the page, PHP on the web server strips your PHP code, interprets it, and uses it to control the HTML that finally reaches the browser. With PHP you can maintain files, manipulate images, and update database contents on the server so your Web pages can interact dynamically with visitors to your site. In the Apache environment, PHP responds faster then Java, another active-site development language. PHP provides quick development times. PHP programmers are more ubiquitous and generally less expensive than Java bean jugglers. PrerequisitesThis tutorial assumes you have access to a Web directory on a local or ISP host, and you have access to PHP and MySQL on a server that also provides tools for you to administer your own databases. You must be able to upload or submit command line or Web-based database queries in order to create and maintain your database. One reasonably-priced ISP that provides this environment with outstanding and easy to use tools, is ApolloHosting.com . PHP Page StructureLet's try a simple PHP page. PHP code is detected by the Web server as all code between the symbols "<?php" and "?>". Lines of code and these tags surrounding them are what I call a code "block". Depending on how the Web server is configured, the opening tag can sometimes be simplified to "<?", but for portability, I always open code blocks with the full "<?php". PHP code blocks may appear anywhere on the page interspersed with the HTML. It is general practice to place functions (subroutines used many places in the page by other code) at the bottom of the page, and group the code that modifies page appearance near the HTML it changes. Apache detects pages it should route to the PHP interpreter by the page file extention ".php". Type the following listing into a text editor and save it as php_test.php in your site's "public_html" or Web root directory, then access the page:
The first few lines create a PHP variable denoted by the word starting with "$" ("$page_name") and set its value to the text string between double quotes. Below, the HTML <title> tag is supplied this value. The "echo" statement functions much like a "print" statement. To find out the differences, and to get more details on other functions we will be demonstrating, see the on-line PHP Function Reference. I keep a link to this handy page in my browser's toolbar. Try replacing the code in the <body> with this and see what happens (after the "!" sign, press return so "strftime("%T")" starts on a new line as shown):
... and here's another way, similar to how you'd print values retrieved into variables from a database:
Looks the same, doesn't it? Notice how the variables substitute in for the "%s" placeholders. To control flow in a program, we use variations of "if" statements:
Here, the test condition is evaluated and if the evaluation produces a positive (0 or higher) result, the code between the braces ("{ }") is executed. The double-slash indicates a comment line. Nothing on a comment line will be executed. Test conditions can be whether a variable is present or not ["if ($variable)"] or if the variable equals a certain string or quantity ["if ($variable == 'Rik')" or "if ($age <= 30) { $category = 'young'; }"] or if the variable is NOT equal or present ["if (!$sexy) { $ignore = 1; }" or "if ($variable != 5)"]. Here's a variation that provides an alternative block of code to execute if the test-condition fails:
What's also interesting about the above is that the paragraph of italic HTML code will not appear in the page if the test-condition is true! It is isolated from the browser until the test-condition fails because it is between braces. Notice the closing brace for the "else", in a re-opened PHP tag block. So far, you've been able to generate text content on an HTML page, and used a variable to supply the page's title. OK, now let's get into the meat of PHP and MySQL. In the process, we'll use other aspects of this powerful language. The ProjectAn interactive guestbook requires the use of several major capabilities of PHP and makes a good choice for a tutorial. Basic features of our example guestbook are:
Set up the databaseBefore I code any pages for an application, I build the database so I can have some real data to display. MySQL databases consist of a database name (we'll call ours "guestbook") under which one or more data tables reside. For our tutorial, the database "guestbook" will consist of only one table, "Messages". I usually use capitalized names for tables and fields so they are easily distinguished from code variables in a listing, which I DO NOT capitalize. The first step in building a database is designing the table structure. There are some basic requirements but in general you can do what you like. The easiest way to start is to build the table as a "CREATE" command that can be slurped into MySQL rather than creating the fields one at a time from the commandline. We are going to store a first name, last name, email address, Web address, the visitor's city, state and country of residence, and the text of the guestbook entry. Each entry will also automatically be numbered ("Entryid") and time- and date-stamped. Type the following into a text file called "create_messages.sql": CREATE TABLE Messages ( Entryid int(5) NOT NULL auto_increment, Time varchar(8) NOT NULL default '', Date varchar(10) NOT NULL default '', Fname varchar(20) default NULL, Lname varchar(20) default NULL, Email varchar(40) default NULL, URL varchar(80) default NULL, City varchar(30) default NULL, State varchar(30) default NULL, Country varchar(20) default NULL, Comments text, PRIMARY KEY (Entryid) ) TYPE=MyISAM; To create the database, use your ISP's on-line tool or issue commands from a terminal logged in via SSH (not many smart ISPs use TELNET anymore!) For the purpose of the tutorial, I will use commandline mode examples. Insert your account's username and password where indicated. The dollar-sign ("$") prefix indicates you are logged in as a user of the system. (If you are trying this out on your own home Linux server, use "root" as the user, and a password is probably not required.) $ mysql -u user -p create guestbook Enter password ****** mysql> : That creates our database. Hosts like Apollo sometimes automatically create the database for your entire site from the site name, as in "gadget-zone_com" for the site "Gadget-Zone.com". Now upload the CREATE file you made and use it to build the Messages table. Enter the command below, then enter your password when (and if) prompted: $ mysql -u user -p guestbook < create_messages.sql Enter password ****** mysql> : Other ways to create a database table are to execute the SQL statements above using a database tool on your host, or put the SQL statements in a PHP script and execute the script. This method can be used if you do not have a terminal client or SSH access to the host. For instance, simply put this code in a page called "setup.php", alter the values at the top for your your host setup, and upload it to your site using your FTP client:
Now access it with your browser: http://yourdomain.com/setup.php You can only run this script successfully once. If the table "Messages" exists already, the SQL statements will not be executed. If you get an error in the process of creating the table, you will have to use some tool on your host to delete the table and try again. Unless you got an error, you now have a database table to store guestbook entries. Copyright 2003 Richard Nilsson. Verbatim copying and redistribution of this entire article are permitted without royalty in any medium provided this notice is preserved. |
|