<?php
// build the basis for the query
$sql = '
SELECT
`id`,
`title`,
`total`
FROM
`my_table`
';
// check for sort field
$sort_by = isset($_GET['s']) ? $_GET['s'] : false;
// validate the sort field (avoid Bobby Tables!) and provide default
switch ($sort_by) {
case 'title':
case 'id':
case 'total':
break;
default:
$sort_by = 'id';
}
$sql .= ' ORDER BY '.$sort_by.' ';
// get the direction, or use the default
$direction = isset($_GET['d']) ? $_GET['d'] : false;
if ($direction != 'ASC' && $direction != 'DESC')
$direction = 'DESC';
$sql .= $direction;
// execute query, get results
$res = mysql_query($sql);
$results = array();
if ($res) {
while ($r = mysql_fetch_assoc($res)) {
$results[] = $r;
}
}
// used in table heading to indicate sort direciton
$sort_arrow = ($direction == 'ASC' ? '<img src="up_arrow.png" />' : '<img src="down_arrow.png" />');
// used to build urls to reverse the current sort direction
$reverse_direction = ($direction == 'DESC' ? 'ASC' : 'DESC');
?>
<table>
<thead>
<th scope="col" class="<?php echo $sort_by == 'id' ? 'sortColumn' : ''; ?>">
<a href="myscript.php?s=id&d=<?php echo $reverse_direction; ?>">ID</a>
<?php echo $sort_by == 'id' ? $sort_arrow : ''; ?>
</th>
<th scope="col" class="<?php echo $sort_by == 'id' ? 'sortColumn' : ''; ?>">
<a href="myscript.php?s=title&d=<?php echo $reverse_direction; ?>">Title</a>
<?php echo $sort_by == 'title' ? $sort_arrow : ''; ?>
</th>
<th scope="col" class="<?php echo $sort_by == 'id' ? 'sortColumn' : ''; ?>">
<a href="myscript.php?s=total&d=<?php echo $reverse_direction; ?>">Total</a>
<?php echo $sort_by == 'total' ? $sort_arrow : ''; ?>
</th>
</thead>
<tbody>
<?php
if (count($results) > 0) {
foreach ($results as $r) {
print '<tr>';
print '<th scope="row">'.$r['id'].'</th>';
print '<td>'.$r['title'].'</td>';
print '<td>'.$r['total'].'</td>';
print '</tr>';
}
} else {
print '<tr><td colspan=3>No results found</td></tr>';
}
?>
</tbody>
</table>
您的表模式/查詢在哪裏?你的PHP代碼在哪裏?向我們展示一些代碼,這是您的嘗試,所以我們可以幫助您解決困難。不要帶我們回到我們的代碼夢想... – Shef