Database Reference
In-Depth Information
print ( "<ol>" );
while ( list ( $item ) = $sth -> fetch ( PDO :: FETCH_NUM ))
print ( "<li>" . htmlspecialchars ( $item ) . "</li>" );
print ( "</ol>" );
The preceding examples generate HTML by interleaving row fetching and output gen‐
eration. It's also possible to separate (decouple) the two operations: retrieve the data
first, and then write the output. Queries tend to vary from list to list, but generating the
list itself often is fairly stereotypical. If you put the list-generation code into a utility
function, you can reuse it for different queries. The function must handle two opera‐
tions: HTML-encoding the items (if they aren't already encoded), and adding the proper
HTML tags. The following PHP function does this. It takes the list items as an array
argument and returns the list as a string:
function make_ordered_list ( $items , $encode = TRUE )
{
$result = "" ;
foreach ( $items as $val )
{
if ( $encode )
$val = htmlspecialchars ( $val );
$result .= "<li> $val </li>" ;
}
return ( "<ol> $result </ol>" );
}
To use the utility function, fetch the data and print the HTML like so:
# fetch items for list
$stmt = "SELECT item FROM ingredient ORDER BY id" ;
$sth = $dbh -> query ( $stmt );
$items = $sth -> fetchAll ( PDO :: FETCH_COLUMN , 0 );
# generate HTML list
print ( make_ordered_list ( $items ));
In Python, write the utility function like this:
def make_ordered_list ( items , encode = True ):
result = ""
for item in items :
if item is None : # handle possibility of NULL item
item = ""
# make sure item is a string, then encode if necessary
item = str ( item )
if encode :
item = cgi . escape ( item , 1 )
result += "<li>" + item + "</li>"
return "<ol>" + result + "</ol>"
And use it like this:
Search WWH ::




Custom Search