没有提供值时选择所有记录

时间:2013-09-02 14:36:05

标签: php mysql sql

我在php中有一个函数可以从MySql数据库中检索和显示工作。

就是这样:

function thisFunction($id,$country,$year){
global $conn;
    $conn = connect();
    $stmt = $conn->prepare("select * from table where id = :id and countryCode = :country and YEAR(addedDate) = :year and status = 0");
    $stmt->execute(array(
        ':id'      => $id,             
        ':country' => $location,
        ':year'    => $year
    ));
}

问题是,有时$id有一个值,有时却没有。当它有一个值时,我想选择具有该值的记录,如果不是,我想选择全部。

如何在那里编写sql,或者执行此操作,以便在有值时,它将仅选择具有该值的记录,并且当没有值时,它将选择all。这是没有选择任何值的部分 - 然后选择所有我被困的地方。

我像任何人一样调用该函数。没有什么独一无二的。

select * from table where id = 9 -- works fine - displays all records where id = 9
select * from table where id = no value supplies - should display all value. How do I do this?

你能帮忙吗?

select * from table where id = * //Does not work

4 个答案:

答案 0 :(得分:2)

如果它是空的,只需删除它:

function thisFunction($id,$country,$year){
    global $conn;

    $conn = connect();

    if (!isset($id) || empty($id))
    {
        $stmt = $conn->prepare("select * from table where countryCode = :country and YEAR(addedDate) = :year and status = 0");
        $stmt->execute(array(      
            ':country' => $location,
            ':year'    => $year
        ));
    }
    else
    {
        $stmt = $conn->prepare("select * from table where id = :id and countryCode = :country and YEAR(addedDate) = :year and status = 0");
        $stmt->execute(array(
            ':id'      => $id,             
            ':country' => $location,
            ':year'    => $year
        ));
    }
}

答案 1 :(得分:1)

select * from table where id = id;

Sample fiddle

答案 2 :(得分:1)

您可以使用以下内容:

function thisFunction($id,$country,$year){

    global $conn;

    $sql_query = "select * from table where status = 0";

    $where_data = array();

    if(isset($id) && $id != '*'){ // Only add this if ID is set to something other than *
        $where_data[':id'] = $id;
        $sql_query .= " AND id = :id";
    }

    if(isset($location)){
        $where_data[':country'] = $location;
        $sql_query .= " AND countryCode = :country";
    }

    if(isset($year)){
        $where_data[':year'] = $year;
        $sql_query .= " AND YEAR(addedDate) = :year"; 
    }

    $conn = connect();
    $stmt = $conn->prepare($sql_query);
    $stmt->execute($where_data);

}

答案 3 :(得分:0)

如果列不为null,您可以选择它们。

select * from table where id is not null