PHP / MySQL从数据库中移出一个表但是从表中排除了一个字段?

时间:2012-08-21 02:11:18

标签: php mysql sql database html-table

我有一个表单,允许用户设置表中数据的排序以及是否增加或减少顺序

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>

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

2 个答案:

答案 0 :(得分:1)

您的查询应如下所示:

SELECT (columns) FROM (table)

不要全部选择,看起来你只需要特定的列。

答案 1 :(得分:1)

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

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

运行这个:

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

...其中hatscatsmargarine将替换为表格中的字段。您可以用这种方式指定任意数量的字段,甚至只能抓取一个字段。