有没有一种更简单的方法可以让我编写代码并执行相同的操作而无需进行这么多查询?我正在尝试添加分页(此处未包含在代码中),它适用于我的 ALL 查询,但 AND / OR 查询给出了有趣的结果,并且变得令人头疼。除此之外,结果的过滤效果很好,只需要分页。
$filter = isset($_POST['filter']) ? $_POST['filter'] : null;
$status = isset($_POST['status']) ? $_POST['status'] : null;
if(empty($filter) && empty($status)) {
//echo 'ALL query';
$sql = 'SELECT * FROM _product JOIN _module_type ON module_type = module_id';
$sth = $link->prepare($sql);
$sth->execute(array());
$result = $sth->fetchall();
} else {
// display result if filter AND status are selected
if(!empty($filter) && !empty($status)) {
//echo 'AND query';
$sql = 'SELECT * FROM _product JOIN _module_type ON module_type = module_id WHERE module_type = :filter AND product_status = :status';
$sth = $link->prepare($sql);
$sth->execute(array(':filter' => $filter, ':status' => $status));
$result = $sth->fetchall();
} else {
// display result if filter OR status are selected
if(!empty($filter) || !empty($status)) {
//echo 'OR query';
$sql = 'SELECT * FROM _product JOIN _module_type ON module_type = module_id WHERE module_type = :filter OR product_status = :status';
$sth = $link->prepare($sql);
$sth->execute(array(':filter' => $filter, ':status' => $status));
$result = $sth->fetchall();
}
}
}
//test sql
echo $sql.'<br />';
$bgcolor = '';
foreach($result as $key => $value) {
if(($bgcolor=='#ffffff') ? $bgcolor='#f1f1f1' : $bgcolor='#ffffff') {
echo '<tr bgcolor="'.$bgcolor.'">';
echo '<td>'.$value['product_id'].'</td>';
echo '<td>'.$value['product_name'].'</td>';
echo '<td>'.$value['product_type'].'</td>';
echo '<td>'.$value['module_name'].'</td>';
echo '<td>'.$value['product_price'].'</td>';
echo '<td>'.$value['product_status'].'</td>';
echo '</tr>';
}
}
echo '</table>';