1

我在 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,或者执行此操作,以便在有值时仅选择具有该值的记录,而当没有值时,它将全选。这是没有选择任何值的部分 - 然后选择我卡住的所有地方。

我像任何人一样调用该函数。那里没有什么独特的。

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

4 回答 4

2

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

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
        ));
    }
}
于 2013-09-02T14:38:27.593 回答
1
select * from table where id = id;

样品小提琴

于 2013-09-02T14:38:08.273 回答
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);

}
于 2013-09-02T14:39:39.553 回答
0

如果该列不为空,您可能会选择它们。

select * from table where id is not null
于 2013-09-02T15:24:39.457 回答