SQL中使用的PHP变量

时间:2014-02-12 15:53:52

标签: php sql

我的代码检查是否有$ GET值,如果没有,则分配所有数组值。 看起来很简单,不知道为什么它不起作用。

if(isset($_GET["smonth"])) {$smonth= $_GET["smonth"];
} 
else {$smonth =12;}  working , but not what I want
else {$smonth =array (1,2,3,4,5,6,7,8,9,10,11) ;}

之后我想在SQL中使用它:

and d.month_of_year = '".$smonth."%'

这就像是

 and month_of_year = (all values of array) or 1 value)

我的问题: 如果活跃的月份可用,最好的检查方法是什么?如果没有,请指定所有月份进行查询。谢谢你

4 个答案:

答案 0 :(得分:0)

in_array和implode的内置PHP函数应该可以解决您的问题:

in_array('1', $_GET["smonth"]); // checks if January is in $_GET["smonth"]
implode("," , $_GET["smonth"]); // Pull all of the values out of $_GET["smonth"] as a A STRING

答案 1 :(得分:0)

尝试使用您的陈述and d.month_of_year IN (" . implode(',', $smonth) . ")

答案 2 :(得分:0)

=运算符检查单个值。如果要检查多个值,请使用in

and d.month_of_year in (".$smonth.")

您还有一个%,可以使用LIKE次查询。

答案 3 :(得分:0)

<?php 

    if(isset($_GET['month'])){
    $month =  date('m');  //This would give you the index of the current month.

    $array = array('01','02','02');

    $query = "select * from table where month = ";
    if(in_array($month,$array)){
        $query = "select * from table where month = '".$month."'";

        //Then query here
    }
    else
    {
    $query = "select * from table";
        $where = "";
        foreach($month as $m){
            $where .= ' month = "'.$m.'" and ';
        }

        //There would be a ending and pls just try remove it

        $query .= $where;

        // then query here
        }


    }
?>