SELECT * FROM table_name WHERE staus == open / pending / closed / all

时间:2014-12-04 17:41:37

标签: php select

如果用户选择了显示全部显示打开,待处理和已关闭的结果。

如果用户选择显示待定显示待处理结果。

是否可以通过一个查询来完成此工作?

<?php

$status = isset($_GET['status']) ? filter_input(INPUT_GET, 'status', FILTER_SANITIZE_STRING) : '';// pending, closed, open, all //

if($status == 'pending' or $status == 'closed' or $status == 'open'){

    $query = 'SELECT * FROM table_name WHERE user = :user AND status = :status ORDER BY dateCreated DESC';
    $select = $db->prepare($query);
    $select->bindParam(':user', $userInfo['username'], PDO::PARAM_STR);
    $select->bindParam(':status', $status, PDO::PARAM_STR);
    $select->execute(); 

}else{

    $query = 'SELECT * FROM table_name WHERE user = :user ORDER BY dateCreated DESC';
    $select = $db->prepare($query);
    $select->bindParam(':user', $userInfo['username'], PDO::PARAM_STR);
    $select->execute(); 

}

?>

2 个答案:

答案 0 :(得分:0)

您可以在准备之前构建SQL字符串。如果$status是您想要的,那么只需添加该子句即可。然后,您可以将数组传递给bindParam

,而不是使用execute()
$query = 'SELECT * FROM table_name WHERE user = :user';
$params = array(
    'user' => $userInfo['username']
);

if(in_array($status, array('pending', 'closed', 'open'))){
    $query .= ' AND status = :status';
    $params['status'] = $status;
}

$query .= ' ORDER BY dateCreated DESC';

$select = $db->prepare($query);
$select->execute($params);

答案 1 :(得分:0)

$status = isset($_GET['status']) ? filter_input(INPUT_GET, 'status', FILTER_SANITIZE_STRING) : '';// pending, closed, open, all //
if($status == 'pending' or $status == 'closed' or $status == 'open')
    $stquery='AND status = :status';
else
    $stquery = '';

$query = 'SELECT * FROM table_name WHERE user = :user '.$status.' ORDER BY dateCreated DESC';
    $select = $db->prepare($query);
    $select->bindParam(':user', $userInfo['username'], PDO::PARAM_STR);

if(!empty($stquery)
    $select->bindParam(':status', $status, PDO::PARAM_STR);

$select->execute();