PHP中的PDO:绑定参数中的问题

时间:2011-06-03 08:43:39

标签: php pdo

我想将(1,2,3)传递给where子句的IN查询。像这样的东西。

$sql = $db->prepare("
    SELECT 
        id, attribution,..........................
    FROM
        filterdaiict
    WHERE Checkbox
        IN (:checkbox)
    HAVING
        distance < :radius
    ORDER BY
        distance ASC
    LIMIT
        0, 50 
");

$sql->bindParam(
    ':checkbox',
    GetCheckboxValue ( $value['CHECKBOXLIST'] ),
    PDO::PARAM_STR 
);

其中函数GetCheckboxValue ( $value['CHECKBOXLIST'] )返回类似1,2,3的字符串。 此代码不起作用。我不知道错误在哪里。让我知道。提前致谢。

2 个答案:

答案 0 :(得分:3)

此示例基于SamT上面的答案构建查询字符串,但仍绑定参数。

// Get your IDs into an array
$ids = explode(',', GetCheckboxValue($value['CHECKBOXLIST']));

// Build a list of placeholders that we can use in the query
$params = array();
foreach ($ids as $idx => $val) {
     $key = ':checkbox' . $idx;
     $params[$key] = $val;
}    

// Join the keys to use as placeholders
$querystr = implode(', ', array_keys($params));

// Prepare our statement using the placeholders we made above
$sql = $db->prepare( " SELECT id, attribution,...... .................... 
    FROM filterdaiict where Checkbox IN ($querystr) 
    HAVING distance < :radius 
    ORDER BY distance ASC LIMIT 0, 50 " );

// Bind a value for each key
foreach ($params as $key => &$val) {
    $sql->bindParam(
        $key,
        $val,      
        PDO::PARAM_STR 
    );
 }

答案 1 :(得分:1)

您必须自己构建查询。

$ids = array(1, 2, 3);
$querystr = implode(',', $ids);

$sql = $db->prepare( " SELECT id, attribution,...... .................... 
    FROM filterdaiict where Checkbox IN ($querystr) 
    HAVING distance < :radius 
    ORDER BY distance ASC LIMIT 0, 50 " );