doudou7361 2015-07-19 12:32
浏览 103
已采纳

如果变量等于“all”,则选择列中的所有字段,否则仅选择等于变量的字段

I have this query that shows some buildings that are for sale and where the user can select "plaats" (region) and slaapkamers (number of bedrooms). These are stored in variables and this query works:

$p = $_POST['plaats'];
$s = $_POST['slaapkamers'];

$sSql = "select * from tblpand WHERE PandPostcodeGemeente='". mysql_real_escape_string( $p ) ."' AND PandSlaapkamers='". mysql_real_escape_string( $s ) ."';

This works as long as long as the variable equals a field. For example, if $s equals 3, all buildings with 3 bedrooms are shown. However, there is also an option to select all number of bedrooms ("all"), same with regions, $p is "all" if all regions should be selected. I don't know how to add this to the query. Maybe something like:

$sSql = "select * from tblpand WHERE"If ($p != "all"){ PandPostcodeGemeente='". mysql_real_escape_string( $p ) ."'}" AND "If ($s != "all"){PandSlaapkamers='". mysql_real_escape_string( $s ) ."'}";

This is just a theoretical example, I know this won't work. Any ideas about this? Thank you all.

  • 写回答

2条回答 默认 最新

  • dtvdz911959 2015-07-19 12:39
    关注

    Try this:

    $p = $_POST['plaats'];
    $s = $_POST['slaapkamers'];
    
    $sSql = "select * from tblpand WHERE 1=1";
    if ($p !== 'all') {
        $sSql .= " AND PandPostcodeGemeente='" . mysql_real_escape_string($p) . "'";
    }
    if ($s !== 'all') {
        $sSql .= "AND PandSlaapkamers='" . mysql_real_escape_string($s) . "'";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?