Database Reference
In-Depth Information
<td><c:out
value=
"${row.title}"
/></td>
</tr>
</c:forEach>
</table>
In Perl scripts, the CGI.pm functions
table()
,
tr()
,
td()
, and
th()
produce the table,
row, data cell, and header cell elements. (Special case: To avoid a conflict with the built-
in Perl
tr
character-transliteration function, invoke the
tr()
function that generates a
table row as
Tr()
.) To display the contents of the
cd
table as an HTML table, do this:
my
$sth
=
$dbh
->
prepare
(
"SELECT year, artist, title
FROM cd ORDER BY artist, year"
);
$sth
->
execute
();
my
@rows
;
push
(
@rows
,
Tr
(
th
(
"Year"
),
th
(
"Artist"
),
th
(
"Title"
)));
while
(
my
(
$year
,
$artist
,
$title
)
=
$sth
->
fetchrow_array
())
{
push
(
@rows
,
Tr
(
td
(
escapeHTML
(
$year
)),
td
(
escapeHTML
(
$artist
)),
td
(
escapeHTML
(
$title
))
));
}
print
table
({
-
border
=>
"1"
},
@rows
);
Sometimes a table is easier to read if the rows use alternating colors, particularly if its
cells don't include borders. To do this, add a
style
attribute that sets the background
color to each
<th>
and
<td>
tag, and alternate the color value for each row. This is easy
with a variable that toggles between two values. The following example alternates the
$color
variable between
silver
and
white
:
my
$sth
=
$dbh
->
prepare
(
"SELECT year, artist, title
FROM cd ORDER BY artist, year"
);
$sth
->
execute
();
my
$color
=
"silver"
;
# row-color variable
my
$style
=
"background-color:$color"
;
my
@rows
;
push
(
@rows
,
Tr
(
th
({
-
style
=>
$style
},
"Year"
),
th
({
-
style
=>
$style
},
"Artist"
),
th
({
-
style
=>
$style
},
"Title"
)
));
while
(
my
(
$year
,
$artist
,
$title
)
=
$sth
->
fetchrow_array
())
{
# toggle the row-color variable
$color
=
(
$color
eq
"silver"
?
"white"
:
"silver"
);
$style
=
"background-color:$color"
;
push
(
@rows
,
Tr
(
td
({
-
style
=>
$style
},
escapeHTML
(
$year
)),
td
({
-
style
=>
$style
},
escapeHTML
(
$artist
)),
td
({
-
style
=>
$style
},
escapeHTML
(
$title
))