Returning error condition When using SQL action statements, you cannot assume that your query is always successful. For example: // BAD $statement = “UPDATE myTable SET myField1 = 100 WHERE ID = 1”; $result = $dbi->query($statement); Here the $result object needs to be checked to see if the SQL action operation was successful. The following code takes care of that: // GOOD $statement = “UPDATE myTable SET myField1 = 100 WHERE ID = 1”; $result = $dbi->query($statement); return ($result == DB_OK) ? TRUE : FALSE; This segment returns TRUE if $result is set to DB_OK; otherwise, it returns FALSE. The DB_OK constant is set in the DB.php package used by class.DBI.php dis- cussed in Chapter 4. For our discussion, what is important is that you should test the result of a query to see if database operation was successful or not. Naming fields in INSERT statements When inserting data in tables, many developers do not use field names in the INSERT statement, as the following code shows: $params[1] = 30; $params[2] = 500000; myFunction($params); // BAD function myInsertFunction($params = null) { $stmt = “INSERT INTO myTable VALUES($params[1], $params[2])”; $result = $this->dbi->query($stmt); return ($result == DB_OK) ? TRUE : FALSE; } Chapter 3: PHP Best Practices 51 05 549669 ch03.qxd 4/4/03 9:24 AM Page 51 In this example, the INSERT statement is dependent on the ordering of the para- meters and fields in the database. If the database administrator adds a new field before any of the existing fields, the INSERT statement might fail. To remove such a chance, use the following INSERT statement: // GOOD function myInsertFunction($params = null) { $stmt = “INSERT INTO myTable (AGE, INCOME) VALUES(“ “$params[1], $params[2])”; $result = $this->dbi->query($stmt); return ($result == DB_OK) ? TRUE : FALSE; } Now the INSERT statement uses field list (AGE, INCOME) to identify which fields are being inserted in a row. Efficient update statement When updating data using the UPDATE statement, you need to create a list of key=value pairs to set database fields to respective values. Here’s an example of how not to do this: // BAD function myUpdateFunction($params = null) { $values = “FNAME = ‘“ . $params[‘FNAME’] . “‘,” . “LNAME = ‘“ . $params[‘LNAME’] . “‘,” . “SCHOOL = ‘“ . $params[‘SCHOOL’] . “‘,” . “YEAR = “ . $params[‘YEAR’]; $stmt = “UPDATE myTable SET $values WHERE ID = $params[‘ID’]”; $result = $this->dbi->query($stmt); return ($result == DB_OK) ? TRUE : FALSE; } 52 Part I: Designing PHP Applications 05 549669 ch03.qxd 4/4/03 9:24 AM Page 52 This example is “bad” because the code is not clean or easy to manage if the data- base field list grows or reduces. Here is the better version of the code: // GOOD: function myUpdateFunction($params = null) { $fields = array(‘FNAME’ => ‘text’, ‘LNAME’ => ‘text’, ‘SCHOOL’ => ‘text’, ‘YEAR’ => ‘number’ ); while(list($k, $v) = each($fields)) { if (!strcmp($v, ‘text’)) { $params[$k] = $this->dbi->quote(addslashes($params[$k])); } $valueList[] = $k . ‘=’ . $params[$k]; } $values = implode(‘,’, $valueList); $stmt = “UPDATE myTable SET $values WHERE ID = $params[‘ID’]”; $result = $this->dbi->query($stmt); return ($result == DB_OK) ? TRUE : FALSE; } In this example, the field list is stored in $fields as a field_name=field_type pair. The string data is first slash-escaped and quoted and all data are stored in $valueList as field_name=field_value pairs. A comma-separated list called $values is created from the $valueList. The UPDATE statement then becomes quite simple and is very readable and easy to maintain. If a new field is added to the database, you simply update the $fields array; similarly, if a field is removed, removing it from the $fields array takes care of it all. Chapter 3: PHP Best Practices 53 05 549669 ch03.qxd 4/4/03 9:24 AM Page 53 Best Practices for User Interface A user interface (UI) is a big part of the applications that we’re going to design and develop throughout this book. Here are some very good practices that you should consider when developing code that has UI. Avoiding HTML in application code Don’t use HTML tags in PHP code. HTML tags make the code very unmanageable. For example: echo “<html>”; echo “<head><title>My Document</title></head>”; echo “<body bgcolor=’#ffffff’>”; echo “<h1>Hello $user</h1>”; echo “</body>”; echo “</html>”; If the above code is in a PHP script, the HTML can only be changed by modifying the PHP code itself. This means the person changing the code needs to know PHP, which means someone with good HTML skill but no PHP skill cannot change the interface, which is very common. This is why it is not manageable. When generating HTML interface for Web application, you should use HTML tem- plate object. For example, below I show you how to use the PHPLIB Template class (found in template.inc) to create HTML template objects to display HTML page where page is external to the code. $TEMPLATE_DIR = ‘/some/path’; $MY_TEMPLATE = ‘screen.ihtml’; $template = new Template($TEMPLATE_DIR); $template->set_file(‘fh’, $MY_TEMPLATE); $template->set_block (‘fh’, ‘mainBlock’, ‘main’); $template->set_var(‘USERNAME’, $user); $template->parse(‘main’,’mainBlock’, false); $template->pparse(‘output’, ‘fh’); This example code does the following: ◆ Assigns a variable called $TEMPLATE_DIR to /some/path and $MY_TEMPLATE variable to screen.ihtml. ◆ Creates a Template object that points to $MY_TEMPLATE file (shown in Listing 3-1) in the $TEMPLATE_DIR directory. 54 Part I: Designing PHP Applications 05 549669 ch03.qxd 4/4/03 9:24 AM Page 54 ◆ Uses the set_block() method to assign the variable name ‘main’ to a block called mainBlock, which is identified in the template using <! BEGIN mainBlock > and <! END mainBlock > tags. ◆ Uses the set_var() method to replace a template tag called {USERNAME} with data from $user variable. ◆ Uses the parse() method to parse mainBlock within the template. ◆ Parses the template to insert the contents of the already parsed mainBlock in the output, and uses the pparse() method to print all the contents of the template. Listing 3-1: screen.ihtml <html> <head><title>My Document</title></head> <! BEGIN mainBlock > <body bgcolor=”#ffffff”> <h1>Hello {USERNAME} </h1> </body> <! END mainBlock > </html> Generating HTML combo lists in application code When using HTML interface, especially Web forms to collect input data from users, it is often necessary to display drop-down combo list (select) boxes. Ideally, the PHP code responsible for generating the combo boxes should be free from HTML tags so that total interface control remains within the HTML template. Here is a code segment that creates a combo list using PHP but includes HTML tags: //BAD: $TEMPLATE_DIR = ‘/some/path’; $MY_TEMPLATE = ‘bad_screen.ihtml’; $cmdArray = array( ‘1’ => ‘Add’, ‘2’ => ‘Modify’, ‘3’ => ‘Delete’ ); Chapter 3: PHP Best Practices 55 05 549669 ch03.qxd 4/4/03 9:24 AM Page 55 . in a PHP script, the HTML can only be changed by modifying the PHP code itself. This means the person changing the code needs to know PHP, which means someone with good HTML skill but no PHP skill. is set to DB_OK; otherwise, it returns FALSE. The DB_OK constant is set in the DB .php package used by class.DBI .php dis- cussed in Chapter 4. For our discussion, what is important is that you should. using PHP but includes HTML tags: //BAD: $TEMPLATE_DIR = ‘/some/path’; $MY_TEMPLATE = ‘bad_screen.ihtml’; $cmdArray = array( ‘1’ => ‘Add’, ‘2’ => ‘Modify’, ‘3’ => ‘Delete’ ); Chapter 3: PHP