如何使用下拉菜单更改SQL查询中的值?

时间:2015-01-09 21:49:02

标签: php mysql drop-down-menu

目前我有2页显示用户信息表。 2页中唯一的区别是SQL查询中的值。我想要做的只有一个页面,并使用下拉菜单选择我想要显示的结果。

我目前有:

page1.php中

<table>
<tr>
<th>Username</th>
<th>level</th>
</tr>
<?php
try {

    $stmt = $db->query('SELECT username, level, FROM members WHERE level < 5 ORDER BY username');
    while($row = $stmt->fetch()){

        echo '<tr>';
        echo '<td>'.$row['username'].'</td>';
        echo '<td>'.$row['level'].'</td>';
        echo '</tr>';

    }

} catch(PDOException $e) {
    echo $e->getMessage();
}
?>
</table>

使page2.php

 <table>
<tr>
<th>Username</th>
<th>level</th>
</tr>
<?php
try {

    $stmt = $db->query('SELECT username, level, FROM members WHERE level > 4 ORDER BY username');
    while($row = $stmt->fetch()){

        echo '<tr>';
        echo '<td>'.$row['username'].'</td>';
        echo '<td>'.$row['level'].'</td>';
        echo '</tr>';

    }

} catch(PDOException $e) {
    echo $e->getMessage();
}
?>
</table>

差异是&#39;&lt; 5&#39;和&#39;&gt; 4&#39;

如何在下拉菜单中将这两个值设置为选项,并缩小为单个页面?

1 个答案:

答案 0 :(得分:0)

考虑到你将使用包含select的POST表单,你可以这样做:

// first the select
// TODO: enclose this in a form directed towards your php script
<select name="choice">
  <!--here two options with your desired values-->
</select>
<input type="submit" value="show rows">

然后在第一个<table>

之前捕获该值
$choice = filter_input(INPUT_POST,"choice",\FILTER_SANITIZE_STRING);

以便您可以将它提供给将运行您的sql的函数:

function makeRows($choice) {
  switch ($choice) {
  case "1":
    $where = "level > 4";
    break;
  case "2":
    $where = "level < 5";
    break;
  default:
    throw new \Exception("that choice was not defined");
  }
  $stmt = $db->query('SELECT username, level, FROM members WHERE '.$choice.' ORDER BY username');
  while ($row = $stmt->fetch()) {
    echo '<tr>';
    echo '<td>'.$row['username'].'</td>';
    echo '<td>'.$row['level'].'</td>';
    echo '</tr>';
  }
}

在根据外部输入的结果执行sql时必须小心,以便永远不会将直接输入连接到您的sql中。看看我如何列入白名单&#34;将要执行的sql。

如何使用它:

// here put the form you've made containing the select
<table>
<tr>
<th>Username</th>
<th>level</th>
</tr>
<?php
$choice = filter_input(INPUT_POST,"choice",\FILTER_SANITIZE_STRING);
try {
  makeRows($choice);
}
} catch(PDOException $e) {
  echo $e->getMessage();
}
?>
</table>

确保在脚本中包含函数定义...