使用PDO使用多个IN语句传递多个值

时间:2016-05-19 10:07:01

标签: php pdo

我在将多个值传递到单个IN语句时没有遇到任何问题,但是当我在一个语句中有多个IN语句时,它就是我在努力的地方。

以下是我为单个IN语句执行的操作:

$sql = "SELECT *
FROM x
INNER JOIN y
ON x.id = y.d_id";

if (isset($_GET['c'])) {

    $catVals = explode(',', $_GET['c']);
    $catValsPlaceholder = implode(',', array_fill(0, count($catVals), '?'));

    $sql .= " WHERE y.category IN ($catValsPlaceholder)";

} else {

}

$sql .= " GROUP BY y.d_id
ORDER BY x.updated ASC
LIMIT 1000";

$sth = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));

if(isset($_GET['c'])) {

    $sth->execute($catVals);
}

$result = $sth->fetchAll(PDO::FETCH_ASSOC);   

但是当我添加另一个IN查询时,我不确定如何使用execute()执行它们。一些上下文,我从我的应用程序传递变量,所以c = a,b,c,d或d = value,value2,value3

if (isset($_GET['c']) && isset($_GET['d'])) {

    $catVals = explode(',', $_GET['c']);
    $catValsPlaceholder = implode(',', array_fill(0, count($catVals), '?'));

    $typeVals= explode(',', $_GET['d']);
    $typePlaceholder= implode(',', array_fill(0, count($typeVals), '?'));

    $sql .= " WHERE y.category IN ($catValsPlaceholder)";
    $sql .= " AND y.type IN ($typePlaceholder)";

}

1 个答案:

答案 0 :(得分:2)

为了让这个完全动态,我会这样做:

$where = array();
$values = array();

if (isset($_GET['c'])) {
    $catVals = explode(',', $_GET['c']);
    $catValsPlaceholder = implode(',', array_fill(0, count($catVals), '?'));
    $where[] = "y.category IN ($catValsPlaceholder)";
    $values = array_merge( $values, $catVals );
}

if (isset($_GET['d'])) {
    $typeVals= explode(',', $_GET['d']);
    $typePlaceholder= implode(',', array_fill(0, count($typeVals), '?'));
    $where[] = "y.type IN ($typePlaceholder)";
    $values = array_merge( $values, $typeVals );
}

// add more conditions

if (sizeof($where > 0))
    $sql .= " WHERE " . implode( " AND ", $where );
}

// then, later:
$sth->execute( $values );