0

我有一个表格,允许用户设置表格中数据的排序方式以及它是增加还是减少顺序

http://damiensplace.co.uk/test/requestTableDisplay.htm

但是我希望用户选择排除字段(年龄等级)表单设置变量,但一直在绞尽脑汁思考如何做到这一点,但我想出的唯一方法并不整洁,因为我基本上需要编写两段代码我错过了一个技巧?

<html><head><title>MySQL Table Viewer</title></head><body>
<?php
$db_host = '****';
$db_user = '***';
$db_pwd = '***';

$sortOn = $_POST['SortOn'];
$sortIn = $_POST['SortIn'];

$database = '****';
$table = '***';

if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// sending query
$result = mysql_query("SELECT * FROM {$table} order by {$sortOn} {$sortIn}");
if (!$result) {
    die("Query to show fields from table failed");
}

$fields_num = mysql_num_fields($result);

echo "<h1>Table: {$table}</h1>";
echo "<table border='1'><tr>";
// printing table headers
for($i=0; $i<$fields_num; $i++)
{
    $field = mysql_fetch_field($result);
    echo "<td>{$field->name}</td>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
    echo "<tr>";

    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
    foreach($row as $cell)
        echo "<td>$cell</td>";

    echo "</tr>\n";
}
mysql_free_result($result);
?>
</body></html>

如果有人能指出我正确的方向,我将不胜感激

4

2 回答 2

1

您应该有如下查询:

SELECT (columns) FROM (table)

不要全选,看来您只想要特定的列。

于 2012-08-21T02:19:21.853 回答
1

很简单。而不是运行此查询:

SELECT * FROM {$table} order by {$sortOn} {$sortIn}

运行这个:

"SELECT hats, cats, margarine FROM {$table} order by {$sortOn} {$sortIn}

...where hatscats并且margarine将被表中的字段替换。您可以通过这种方式指定任意数量的字段,甚至可以只抓取一个字段。

于 2012-08-21T02:19:24.827 回答