我已经制作了这个 php 代码来过滤来自 mysql 数据库的结果。它工作得很好,但我确信这不是实现预期结果的最有效方式(或正确使用语言)。我正在尽我最大的努力在编写代码方面变得“好”,并希望得到一些关于如何更好地做到这一点的反馈。
$filter = "";
if (isset($_POST['submit']))
{
$aircraft_reg = "";
$prefix = "";
$part_number = "";
$flight_control = "";
if(!empty($_POST['aircraft_reg']))
{
$aircraft_reg = "aircraft_reg = '" . $_POST['aircraft_reg'] . "'";
}
if(!empty($_POST['prefix']))
{
$prefix = "prefix = '" . $_POST['prefix'] . "'";
}
if(!empty($_POST['part_number']))
{
$part_number = "part_number = '" . $_POST['part_number'] . "'";
}
if(!empty($_POST['flight_control']))
{
$flight_control = "flight_control = '" . $_POST['flight_control'] . "'";
}
if ($aircraft_reg != "" && ($prefix != "" || $part_number != "" || $flight_control != ""))
{
$a = " AND ";
}
else
{
$a = "";
}
if ($prefix != "" && ($part_number != "" || $flight_control != ""))
{
$b = " AND ";
}
else
{
$b = "";
}
if ($part_number != "" && $flight_control != "")
{
$c = " AND ";
}
else
{
$c = "";
}
if ($aircraft_reg != "" || $prefix != "" || $part_number != "" || $flight_control != "")
{
$filter = "WHERE " . $aircraft_reg . $a . $prefix . $b . $part_number . $c . $flight_control;
}
}
$result = mysql_query("SELECT * FROM installed $filter ORDER BY aircraft_reg , part_number, date_installed ASC");