Database Reference
In-Depth Information
the sports reporter Becky Winthrop with an email address of
bwinthrop@wrrr-
news.com
becomes an entry in the listing that looks like this:
Sports:
<a
href=
"mailto:bwinthrop@wrrr-news.com"
>
Becky Winthrop
</a>
It's easy to use the table's contents to produce such a directory. First, put the code to
generate an email link into a helper function because that operation is likely to be useful
in multiple scripts. In Perl, the function looks like this:
sub
make_email_link
{
my
(
$name
,
$addr
)
=
@_
;
$name
=
escapeHTML
(
$name
);
# return name as static text if address is undef or empty
return
$name
if
!
defined
(
$addr
)
||
$addr
eq
""
;
# return a hyperlink otherwise
return
a
({
-
href
=>
"mailto:$addr"
},
$name
);
}
The function handles instances where the person has no email address by returning just
the name as static text. To use the function, write a loop that pulls out names and ad‐
dresses and displays each email link preceded by the staff member's department:
my
$stmt
=
"SELECT department, name, email FROM newsstaff
ORDER BY department, name"
;
my
$sth
=
$dbh
->
prepare
(
$stmt
);
$sth
->
execute
();
my
@items
;
while
(
my
(
$dept
,
$name
,
$email
)
=
$sth
->
fetchrow_array
())
{
push
(
@items
,
escapeHTML
(
$dept
)
.
": "
.
make_email_link
(
$name
,
$email
));
}
print
ul
(
li
(
\
@items
));
Equivalent email link generator functions for Ruby, PHP, and Python are similar.
For a JSP page, produce the
newsstaff
listing as follows:
<sql:query
dataSource=
"${conn}"
var=
"rs"
>
SELECT department, name, email
FROM newsstaff
ORDER BY department, name
</sql:query>
<ul>
<c:forEach
items=
"${rs.rows}"
var=
"row"
>
<li>
<c:out
value=
"${row.department}"
/>
:
<c:set
var=
"name"
value=
"${row.name}"
/>
<c:set
var=
"email"
value=
"${row.email}"
/>
<c:choose>