<?php
mysql_connect ("hostname", "username", "password") or die(mysql_error());
mysql_select_db ("addresses") or die(mysql_error();
$sql = "
select
firstname,
lastname,
address,
city,
postcode,
country
from
addresses
order by
lastname asc,
firstname asc";
//run query
$result = @mysql_query($sql) or die (mysql_error());
//derive number of results
$numRows = @mysql_num_rows($result);
//calculate number of tables we will need
$numPages = ceil($numRows/14);
//instantiate a variable to hold the output
$output="";
//create the outer loop for the pages
for($page=0; $page<$numPages; $page++):
//create loop for number of rows per page
$output .= "<table class=\"addresstable\">\r\n";
for($row=0; $row<7; $row++):
$output .= "\t<tr class=\"addressRow\">\r\n";
//create innermost loop for columns
for($column=0; $column<2; $column++):
//we do the work in this loop
$record = @mysql_fetch_assoc($result);
if ($record === false): //end of recordset
$name=$firstname=$lastname=$address=$city=$postcode=$country=" ";
else:
//iterate the $result array to make the output look pretty
foreach ($record as $item=>$val):
if(!empty($val)):
${$item} = nl2br($val) . "<br/>";
else:
${$item} = NULL;
endif;
endforeach;
//format the name right
$name = (empty($record['firstname'])) ? $lastname : $record['firstname'] . " ".$record['lastname'];
endif;
//choose class for the label
$class = $column===0 ? "LH" : "RH";
//output label data
$output .= <<<ITEM
<td class="addressLabel_$class" valign="middle">
<div class="addressee">
$name
</div>
<div class="address">
$address
$city
$postcode
$country
</div>
</td>
ITEM;
endfor; //end innermost loop
$output .= "\t</tr>\r\n";
endfor;//close rows loop
$output .= "</table>\r\n";
endfor; //close outer loop
?>
<head>
<style type="text/css">
html, body {margin:0px; padding: 0px; font:"Times New Roman", Times, serif; font-size:10px;}
.addresstable {page-break-after:always; border-collapse:collapse; position:relative; top:1.59cm; left:0.47cm; right:0.47cm; table-layout:fixed;}
.addressLabel_LH, .addressLabel_RH {table-layout:fixed; width:9.9cm; height:3.81cm; padding-left:1cm; overflow:hidden;}
.addressLabel_RH {margin-left:0.26cm;}
</style>
</head>
<body>
<?=$output?>
</body>