如何显示特色='是'以上所有帖子先发布然后休息?

时间:2016-07-14 09:48:59

标签: php mysql

好的,所以我的这个代码工作得很好,但我希望得到的是首先显示结果,其中post_featured ='是'且不超过10天?

如果任何post_featured的值它仍然位于顶部,但只有当它不超过10天我尝试订购但不知何故它不会工作

我的代码

$search_fields = array('post_area','post_category','post_type'); 
$and_clause = array(); 
$params = array();

foreach($search_fields as $field){
    if(isset($_GET[$field]) && $_GET[$field] != 'All'){
        $and_clause[] = "`$field` = :$field";
        $params[] = array(":$field",$_GET[$field],PDO::PARAM_STR);
    }
}

$where_clause = '';
if(!empty($and_clause)){
    $where_clause = "WHERE " . implode(' AND ', $and_clause);
}

$query = "SELECT COUNT(*) FROM posts $where_clause";

if(empty($params)){
    $stmt = $db->query($query);
}else{
    $stmt = $db->prepare($query);
    foreach($params as $param)    {
        $stmt->bindValue($param[0],$param[1],$param[2]);
    }
    $stmt->execute();
}

$total = $stmt->fetchColumn();
$pages = ceil($total / $per_page);

$page = min($pages, filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, array(
'options' => array(
'default'   => 1,
'min_range' => 1,
),
)));

$offset = ($page - 1)  * $per_page; 

$params[] = array(':per_page',$per_page, PDO::PARAM_INT);
$params[] = array(':offset',$offset, PDO::PARAM_INT);

$query = "SELECT * FROM posts $where_clause ORDER BY postID DESC LIMIT :per_page OFFSET :offset";

if(empty($params)){
    $stmt = $db->query($query);
}else{
    $stmt = $db->prepare($query);
    foreach($params as $param){
        $stmt->bindValue($param[0],$param[1],$param[2]);
    }
    $stmt->execute();
}
$result = $stmt->fetchAll();

1 个答案:

答案 0 :(得分:0)

给出表t

+------+---------------+------------+
| id   | post_featured | dte        |
+------+---------------+------------+
|    1 | yes           | 2016-07-15 |
|    2 | no            | 2016-07-15 |
|    3 | yes           | 2016-07-14 |
|    4 | yes           | 2016-06-15 |
|    5 | no            | 2016-06-15 |
|    1 | yes           | 2016-06-14 |
+------+---------------+------------+

并要求以两种方式排序

select t.*,
        case when t.post_featured = 'yes' and dte >= date_add(curdate() ,interval -10 day) then 1
        else 2
        end as srce
 from t
 order  by srce asc,id desc;

结果

+------+---------------+------------+------+
| id   | post_featured | dte        | srce |
+------+---------------+------------+------+
|    3 | yes           | 2016-07-14 |    1 |
|    1 | yes           | 2016-07-15 |    1 |
|    5 | no            | 2016-06-15 |    2 |
|    4 | yes           | 2016-06-15 |    2 |
|    2 | no            | 2016-07-15 |    2 |
|    1 | yes           | 2016-06-14 |    2 |
+------+---------------+------------+------+