有没有更简单的方法让我编码并执行相同的事情,而不必有太多的查询?我试图添加分页(这里没有包含在代码中),它适用于我的ALL查询,但AND/OR查询给出了有趣的结果,并且正在变得令人头疼。除此之外,对结果进行筛选仅仅需要分页。PDO多过滤器sql查询
$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>';
一行今天早上我也有类似的问题。在这里看到答案:http://stackoverflow.com/questions/11740066/simplify-a-mysql-query-that-can-have-multiple-input-options-using-php – Jim 2012-07-31 19:46:02