1

MySqlデータベースからの検索と表示作業を行うphpの関数があります。

こんな感じです:

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

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

列が null でない場合は、それらを選択できる可能性があります。

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