多个查询字符串参数到mysql查询

时间:2012-09-26 22:18:20

标签: php mysql query-string

我最初有这个工作:

url:http://server/blah.php?FacilityCode=FT

$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
       "FROM ..." .
       "WHERE ..." .
       "AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);

但我想改变这一点,以便人们可以在某种程度上提交查询中的多个值,即:http://server/blah.php?FacilityCode=FT,CC,DD,EE

我尝试将查询更改为“IN”子句而不是“equals”,但我不确定如何获取每个元素周围的'标记。

5 个答案:

答案 0 :(得分:2)

对IN(...)使用implode()函数。

$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";

...将输出:

field IN ('AB', 'CD', 'EF', 'ZE')

+逃避你得到的每一个选项。

答案 1 :(得分:0)

$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);

答案 2 :(得分:0)

如果您尝试创建一个如下所示的字符串:'AB','CD','EF','ZE'

在放入查询之前尝试此操作:

$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);

答案 3 :(得分:0)

我根据你的查询写了这个,但我仍然没有得到这部分查询“AND('”。$ facilitycode。“'=''',无论如何你需要检查$ _GET数据是否有”,“和if是否通过“,”将该变量爆炸,以便您可以为$ _GET数据中以“,”分隔的所有内容添加OR clausule。

之后,通过对爆炸数组中的每个元素执行foreach来形成查询,如下所示:

<?php

$facilitycode = $_GET["FacilityCode"];

$facility_number_chk = strpos($facilitycode, ",");

if ($facility_number_chk > -1) {

    $facilitycode = explode(",", $facilitycode);

    $sql = "SELECT ..." .
    "FROM ..." .
    "WHERE ..." .
    "AND ('" . $facilitycode . "' = ''";

    foreach($facilitycode as $facode) {

        $facode = mysql_real_escape_string($facode);

        $sql .= " OR Facility.FacilityCode = '". $facode . "'";

    }

    $sql .= "')";

}
else {

    $facilitycode = mysql_real_escape_string($facilitycode);

    $sql = "SELECT ..." .
    "FROM ..." .
    "WHERE ..." .
    "AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";

}

$result = mysql_query($sql);

如果$ _GET数据中只有一个元素,那么就像我对常规查询所做的一样。

答案 4 :(得分:0)

我最终结合使用了一些答案。基本上我在“,”上爆炸,然后做了一个foreach来添加'标记并调用escape_string,然后将其内爆。

$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
  $additionalfilter = '';
}
else {
  $facilitycodearray = explode(",", $facilitycodes);
  foreach($facilitycodearray as &$facilitycode) {
    $facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
  }
  $facilitycodesformatted = implode(",", $facilitycodearray);
  $additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}

$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;