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?. Naming fields in
Trang 1Returning 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 $resultobject 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_OKconstant 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 INSERTstatement, 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;
}
Trang 2In this example, the INSERTstatement 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 INSERTstatement might fail To remove such
a chance, use the following INSERTstatement:
// 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 INSERTstatement 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=valuepairs 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;
}
Trang 3This 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 $fieldsas 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
$valuesis created from the $valueList The UPDATEstatement 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 $fieldsarray takes care of it all
Trang 4Best 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 Temtem-plate 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_DIRto /some/path and
$MY_TEMPLATEvariable to screen.ihtml
◆ Creates a Template object that points to $MY_TEMPLATEfile (shown in Listing 3-1) in the $TEMPLATE_DIRdirectory
Trang 5◆ 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 $uservariable
◆ Uses the parse()method to parse mainBlockwithin 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’
);