Database Reference
In-Depth Information
stmt = "SELECT phrase_val FROM phrase ORDER BY phrase_val"
dbh . execute ( stmt ) do | sth |
sth . fetch do | row |
# make sure that the value is a string
phrase = row [ 0 ]. to_s
# URL-encode the phrase value for use in the URL
url = "/cgi-bin/mysearch.rb?phrase=" + CGI . escape ( phrase )
# HTML-encode the phrase value for use in the link label
label = CGI . escapeHTML ( phrase )
page << cgi . a ( "href" => url ) { label } + cgi . br
end
end
page is used here as a variable that “accumulates” page content and that eventually you
pass to cgi.out to display the page.
PHP. In PHP, the htmlspecialchars() and urlencode() functions perform HTML-
encoding and URL-encoding. Use them as follows:
$stmt = "SELECT phrase_val FROM phrase ORDER BY phrase_val" ;
$sth = $dbh -> query ( $stmt );
while ( list ( $phrase ) = $sth -> fetch ( PDO :: FETCH_NUM ))
{
# URL-encode the phrase value for use in the URL
$url = "/mcb/mysearch.php?phrase=" . urlencode ( $phrase );
# HTML-encode the phrase value for use in the link label
$label = htmlspecialchars ( $phrase );
printf ( '<a href="%s">%s</a><br />' , $url , $label );
}
Python. In Python, the cgi and urllib modules contain the relevant encoding methods.
cgi.escape() and urllib.quote() perform HTML-encoding and URL-encoding.
However, both methods raise an exception unless the argument is a string. To deal with
this, apply the str() method to any argument that might not be a string, to force it to
string form and convert None to the string "None" . (If you want None to convert to the
empty string, you must test for it explicitly.) For example:
import cgi
import urllib
stmt = "SELECT phrase_val FROM phrase ORDER BY phrase_val"
cursor = conn . cursor ()
cursor . execute ( stmt )
for ( phrase ,) in cursor :
# make sure that the value is a string
phrase = str ( phrase )
# URL-encode the phrase value for use in the URL
url = "/cgi-bin/mysearch.py?phrase=" + urllib . quote ( phrase )
# HTML-encode the phrase value for use in the link label
label = cgi . escape ( phrase , 1 )
Search WWH ::




Custom Search