Det her eksempel viser teknikken paa en generel maade:
<?php
/*
CREATE TABLE whist (round INTEGER NOT NULL, player VARCHAR(50) NOT NULL, point INTEGER NOT NULL, PRIMARY KEY(round, player));
INSERT INTO whist VALUES(1, 'Alan', 20);
INSERT INTO whist VALUES(1, 'Benny', 10);
INSERT INTO whist VALUES(1, 'Christian', 40);
INSERT INTO whist VALUES(1, 'Dennis', 30);
INSERT INTO whist VALUES(2, 'Alan', 40);
INSERT INTO whist VALUES(2, 'Benny', 20);
INSERT INTO whist VALUES(2, 'Christian', 30);
INSERT INTO whist VALUES(2, 'Dennis', 10);
INSERT INTO whist VALUES(3, 'Alan', 20);
INSERT INTO whist VALUES(3, 'Benny', 40);
INSERT INTO whist VALUES(3, 'Christian', 10);
INSERT INTO whist VALUES(3, 'Dennis', 30);
*/
function get_connection() {
$con = new mysqli('localhost', 'root', '', 'Test');
if(mysqli_connect_errno()) {
die(mysqli_connect_error());
}
return $con;
}
function get_results($sql) {
$con = get_connection();
$stmt = $con->prepare($sql) or die(mysqli_error());
$stmt->execute() or die(mysqli_error());
$rs = $stmt->get_result();
$res = array();
while($row = $rs->fetch_array(MYSQLI_ASSOC)) {
$res[] = $row;
}
$stmt->close();
$con->close();
return $res;
}
function display_header($grp, $vals) {
echo "<table>\r\n";
echo "<tr>\r\n";
echo "<th>$grp</th>\r\n";
echo "<th>$vals</th>\r\n";
echo "</tr>\r\n";
}
function display_group_item($item) {
echo "<td>$item</td>\r\n";
}
function display_value_item($item) {
echo "<td>$item</td>\r\n";
}
function display_footer() {
echo "</table>\r\n";
}
function show_horizontal($data, $grpfld, $valfld1, $valfld2) {
$prev = '';
$vals = array();
foreach($data as $res) {
if($res[$grpfld] != $prev) {
if(count($vals) > 0) {
display_value_item(implode(',', $vals));
$vals = array();
}
display_group_item($res[$grpfld]);
$prev = $res[$grpfld];
}
$vals[] = ($res[$valfld1] . ':' . $res[$valfld2]);
}
if(count($vals) > 0) {
display_value_item(implode(',', $vals));
$vals = array();
}
}
function show_rounds() {
$data = get_results('SELECT round, player, point FROM whist ORDER BY round, player');
display_header('Round', 'Result');
show_horizontal($data, 'round', 'player', 'point');
display_footer();
}
function show_players() {
$data = get_results('SELECT round, player, point FROM whist ORDER BY player, round');
display_header('Player', 'Result');
show_horizontal($data, 'player', 'round', 'point');
display_footer();
}
show_rounds();
show_players();
?>
output:
<table>
<tr>
<th>Round</th>
<th>Result</th>
</tr>
<td>1</td>
<td>Alan:20,Benny:10,Christian:40,Dennis:30</td>
<td>2</td>
<td>Alan:40,Benny:20,Christian:30,Dennis:10</td>
<td>3</td>
<td>Alan:20,Benny:40,Christian:10,Dennis:30</td>
</table>
<table>
<tr>
<th>Player</th>
<th>Result</th>
</tr>
<td>Alan</td>
<td>1:20,2:40,3:20</td>
<td>Benny</td>
<td>1:10,2:20,3:40</td>
<td>Christian</td>
<td>1:40,2:30,3:10</td>
<td>Dennis</td>
<td>1:30,2:10,3:30</td>
</table>