A simple PHP script

Jul 23, 2009 Author: City Hall

If PHP provided only the capability of producing what is essentially static HTML by means of print statements, it wouldn’t be very useful. PHP’s power is that it generates dynamic pages: output that can vary from one invocation of a script to the next.The script described in this section shows a simple example of this capability. It’s still relatively short, but a bit more substantial than the previous examples. It shows how easily you can access a MySQL database from PHP and use the results of a query in a Web page.The script forms a simple basis for a home page for the Historical League Web site.As we go on, we’ll make the script a bit more elaborate, but for now all it does is display a short welcome message and a count of the current League membership:

<html>
<head>
<title>U.S. Historical League</title>
</head>
<body bgcolor="white">
<p>Welcome to the U.S. Historical League Web Site.

 

<?php # USHL home page try { $dbh = new PDO("mysql:host=localhost;dbname=sampdb", "sampadm", "secret"); $dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sth = $dbh->query ("SELECT COUNT(*) FROM member"); $count = $sth->fetchColumn (0);print ("

The League currently has $count members.</p>"); $dbh = NULL; # close connection}catch (PDOException $e) { } # empty handler (catch but ignore errors)?> </body> </html>

The welcome message is just static text, so it’s easiest to write it as literal HTML.The membership count, on the other hand, is dynamic and changes over time, so it must be determined at execution time by querying the member table in the sampdb database.To perform that task, the code within the opening and closing script tags follows these steps:

1. Opens a connection to the MySQL server and makes the sampdb database the default database.

2. Enables exceptions for subsequent PDO calls so that errors can be caught easily without testing for them explicitly.

3. Sends a query to the server to determine how many members the Historical League has at the moment (assessed as the number of rows in the member table).

4. Uses the query result to construct a message containing the membership count.

5. Closes the connection to the MySQL server.

The script just shown can be found as the file named index.php in the phpapi/ushl directory of the sampdb distribution. Change the connection parameters as necessary, install a copy of the script as index.php in the ushl directory of your Web server’s document tree, and request it from your browser using either of these URLs (changing the hostname and pathname as appropriate for your own Web server):

http://localhost/ushl/

http://localhost/ushl/index.php

Let’s break down the script into pieces to see how it works.The first step is to connect to the server:

$dbh = new PDO("mysql:host=localhost;dbname=sampdb", "sampadm", "secret");

new PDO() invokes the constructor for the PDO class.The constructor attempts to connect to the database server and raises an exception if it fails. Otherwise, it returns a PDO object that serves as a database handle. The first argument to new PDO() is a string called a “data source name.”The second and third arguments are the username and password to use for connecting to the server, sampadm and secret.The DSN string tells PDO which driver to use, followed by driverspecific parameters. For MySQL, the driver name is mysql, and the parameters are the host where the server is running and the database to select as the default database.The DSN shown indicates that the MySQL server host and default database are localhost and sampdb. Both parameters following the colon are optional.The default value for host is localhost, so this parameter actually could have been omitted. If you omit dbname, no default database is selected. (The DSN can take other forms, and other parameters are allowed. For details, see Appendix I [online].) Perhaps it makes you nervous that the username and password are embedded in the script for all to see.And, indeed, it should. It’s true that the name and password don’t appear in the resulting Web page that is sent to the client, because the script’s contents are replaced by its output. Nevertheless, if the Web server becomes misconfigured somehow and fails to recognize that your script needs to be processed by PHP, it will send the script as plain text, which exposes the connection parameters. The database handle returned by new PDO() becomes the means for further interaction with the MySQL server, such as issuing SQL statements to be executed.After a successful connection, the default error mode for PDO calls is to fail silently, which requires that you check for errors explicitly.To make it easier to handle problems, the script enables exceptions for PDO errors:

$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

With exceptions enabled, a try/catch construct can be used to “route” errors to an exception handler without explicit tests. If you don’t use try/catch, exceptions terminate your script. The script next sends the member-counting query to the server by invoking the database handle’s query() method, and then extracts and displays the result:

$sth = $dbh->query ("SELECT COUNT(*) FROM member");
$count = $sth->fetchColumn (0);
print ("<p>The League currently has $count members.</p>");

The query() method sends the query to the server to be executed. Note that the query string contains no terminating semicolon character or \g or \G sequence, in contrast to the way you issue statements from within the mysql program. query() is used for statements that return rows. (Use a different method, exec(), for statements that modify rows.) query() returns a PDOStatement object that is a statement handle for manipulating the result set. For the query shown, the result set consists of a single row with a single column value representing the membership count.The script invokes the $sth object’s fetchColumn() method to fetch the row and extract the first column (column 0). After printing the count, the script closes the connection to the server by setting the database handle to NULL.This is optional. If you don’t close the connection, PHP closes it when the script terminates. The code for interacting with MySQL occurs within a try block so that any exception raised for an error can be caught and handled by the corresponding catch block. The connection attempt raises an exception automatically if it fails, and the setAttribute() call enables exceptions for any subsequent PDO calls that fail.The catch block in the example is empty, so its effect is to trap and ignore errors.The script writes no message for an error because printing the membership count is ancillary to the greeting presented by the home page.

tags: Simple PHP script

views 3489
  1. Add New Comment