输入值和选择返回数据

时间:2012-07-09 17:58:23

标签: php html

我正在尝试创建一个网页,用户可以在其中提交他们知道的信息并选择他们想要返回的信息。例如,如果他们知道提交的ID号,他们可以输入它并要求返回的值是ID号和产品名。

正在检索的信息存储在MySQL数据库中,并且html页面使用选择菜单,文本框和复选框进行布局(以便用户可以选择名称或输入其他信息,然后使用复选框以选择他们想要返回的其他信息。)

这是相关的html:

<table><tr>
<form name="input" method="post" action="next.php">
<td width="120">Flowcell ID:<br />
<select name = "Flowcell_ID">
<option disabled="disabled" selected="selected">
Select...
</option>
<?php
$link = mysqli_connect("localhost","user","pass","db");
$query = "SELECT DISTINCT ID FROM table";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)){
$id = $row['ID'];
echo "<option value=\"$id\">$id</option>";
}
mysqli_close($link);
?>
</select></td>
</tr><tr>
<td width="120">Name:<input type="text" name="Name" /></td>
</tr><tr>
<td width="120">Date:<input type="text" name="Date" /></td>
</tr><tr>
<td width="120">Group:<input type="text" name="Group" /></td>
</tr><tr>
<td width="120"><input type="checkbox" name="options[]" value="ID">ID</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Name">Name</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Date">Date</input></td>
<td width="120"><input type="checkbox" name="options[]" value="Group">Group</input></td>
</tr></table>

到目前为止我唯一的php是:

$id = $_POST['ID'];
$name = $_POST['Name'];
$date = $_POST['Date'];
$group = $_POST['Group'];

如何生成看起来像

的MySQL查询
SELECT [checked checkboxes] FROM table WHERE [information field] = [user-entered information]

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以逐步构建查询:

$fields = array(
   'ID'   => 'id',
   'Name' => 'name',
   'Date' => 'date',
   'Group' => 'group',
);

$query = 'SELECT';  // Optional fields to be displayed may go here
$comma = ' ';       // and if they do, start with $comma = ', ';

$where = array();

foreach($fields as $post => $mysql)
{
    // here we have $post equal to 'ID', our POST field, and
    // $mysql equal to, say, 'Id' -- the MySQL field name.
    // Check whether options['ID'] is set. If so, we must get
    // the _POST[ID] field and check its contents against "Id" field in DB.
    if (in_array($post, $_POST['options']))
    {
        $query .= "$comma$mysql";
        $comma = ', ';
        // Add WHERE condition
        $where[] = "$mysql = '" . mysql_real_escape_string($_POST[$post]) . "'";
    }
}
// $comma, the separator between option fields, also doubles up as a check
// to see whether we have conditions.
// another possibility would be, "if (empty($where))"
if (' ' == $comma)
   die("You must select at least one checkbox!");

$query .= ' FROM table WHERE ';
// Build WHERE condition
$query .= '(' . implode(' AND ', $where).')';

// Other conditions may go here (e.g. " AND record_valid = 1 ")

$query .= ';';