0

我正在尝试创建一个网页,用户可以在其中提交他们知道的信息并选择他们想要返回的信息。例如,如果他们知道提交的 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]

?

谢谢!

4

1 回答 1

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 .= ';';
于 2012-07-09T18:05:06.550 回答