如何仅从mySql表的指定字段中检索数据?

时间:2012-01-19 18:59:49

标签: php mysql

我想显示一个包含数据库中数据的表(在网页中),但只想显示包含用户选择的字段的表。例如:我的表格中共有6个字段(姓名,电子邮件,年龄,地点,性别,职业)。假设我页面上的用户选择姓名,电子邮件和年龄。我希望显示一个包含所有行条目的表,但只包含指定的字段。

这是我到目前为止所写的内容,但似乎没有起作用。

include("init.php");

$fields = $_POST["fields"];
$sorting = trim($_POST["sorting"]);
$filter = trim($_POST["filter"]);

$sql_query = sprintf("select * from applicants where %s order by %s", $filter, $sorting);
$query = mysql_query($sql_query);
$num_rows = mysql_numrows($query);

echo "<table border='1'>";
echo "<tr>";
    foreach($fields as $field) {
        $field = ucfirst($field);
        echo "<th>$field</th>";
    }
echo "</tr>";

for($i = 0; $i < $num_rows; $i++) {
    echo "<tr>";
    while($field = mysql_fetch_field($query)) {
        if(in_array($field->name, $fields)) {
            $data = mysql_result($query, $i, $col);
            echo "<td>$data</td>";
        } else {
            echo "<td>false</td>";
        }
    }
    echo "</tr>";
}

echo "</table>";

2 个答案:

答案 0 :(得分:1)

最简单的方法是修改

select * from applicants

sql查询。 *表示“所有列”。将其更改为:

$sql_query = sprintf("select `name`, `email`,`age` from applicants where %s order by %s", $filter, $sorting);
$query = mysql_query($sql_query);
$num_rows = mysql_numrows($query);

您可以通过以下方式轻松地从$ _POST ['fields']变量中获取此信息(确保您正在逃避!)。

"select `".implode('`,`',$escaped_fields_array)."` from applicants

另外,我只是想确保你已经确认$ _POST ['fields']变量作为关联数组传递(类似)

答案 1 :(得分:1)

您需要使用列名的值设置<option>,然后使用以下代码:

include('init.php');

$fields = $_POST['fields'];
$sorting = trim($_POST['sorting']);
$filter = trim($_POST['filter']);

function filterFields($field) {
  if (in_array($field, array(/* Here you need to add the fields you allowed to post, to prevent attack */))) {
    return '`' . $field . '`';
  } else {
    return 'NULL';
  }
}

$escapedFields = array_map('filterFields', $fields);

// Make the query, here we use 'implode' function to join all array with ','
// Example if we have array('name', 'time'), then the function will return 'name,time'
$query = mysql_query('SELECT ' . implode(',', $escapedFields) . ' FROM `applicants` WHERE ' . $filter . ' ORDER BY ' . $sorting);
// If the query return something, then...
if (mysql_num_rows($query)) {
  echo '<table border='1'>
<tr>';
  // Here we print the table header.
  for ($i = 0, $fieldsLength = sizeof($field); $i < $fieldsLength; ++$i) {
    echo '<th>' . ucfirst($fields[$i]) . '</th>';
  }
  echo '</tr>';

  // Here we print the result.
  while ($result = mysql_fetch_assoc($query)) {
    echo '<tr>';
    $resultKeys = array_keys($result);
    for ($i = 0, $resultKeysLength = sizeof($resultKeys); $i < $resultKeysLength; ++$i) {
      echo '<td>' . $result[$resultKeys[$i]] . '</td>';
    }
    echo '</tr>';
  }
  echo '</table>';
}