如何避免逃避角色" \"在PDO准备的声明中?

时间:2015-08-25 15:53:14

标签: php mysql pdo

我有这个SQL查询:

$sql = "SELECT ac.id AS target_id FROM account AS ac JOIN 
               address_vod__c AS ad 
               ON (ad.account_vod__c = ac.id AND ad.primary_vod__c = 1)  
               WHERE ac.id IN (?)";

我正在尝试从数组中添加IN子句的值,如下所示:

// $values is a huge array containing values

$params = [implode("','", $values)];
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$result = $stmt->fetchAll();

代码正在运行,但我收到了错误的SQL:

SELECT 
    ac.id AS target_id
FROM
    account AS ac
        JOIN
    address_vod__c AS ad ON (ad.account_vod__c = ac.id
        AND ad.primary_vod__c = 1)
WHERE
    ac.id IN ('00180000017rkSfAAI\',\'0018000001GgXTtAAN\',\'0018000001GgXTYAA3')

我期待并且我看起来像:

SELECT 
    ac.id AS target_id
FROM
    account AS ac
        JOIN
    address_vod__c AS ad ON (ad.account_vod__c = ac.id
        AND ad.primary_vod__c = 1)
WHERE
    ac.id IN ('00180000017rkSfAAI','0018000001GgXTtAAN','0018000001GgXTYAA3')

如何避免PDO逃脱字符串?

2 个答案:

答案 0 :(得分:1)

你在做ac.id IN (?)。这告诉数据库您要将一个参数绑定到查询。如果您有多个元素,则需要多个? s:ac.id IN (?,?,?)

您可以做的是动态添加?,然后绑定您需要的每个参数。

$params = implode(',', array_fill(0, count($values), '?'));
$sql = "SELECT ac.id AS target_id FROM account AS ac
    JOIN address_vod__c AS ad ON (ad.account_vod__c = ac.id AND ad.primary_vod__c = 1)
    WHERE ac.id IN ({$params})";

$stmt = $pdo->prepare($sql);
$stmt->execute($values);
$result = $stmt->fetchAll();

答案 1 :(得分:0)

你应该破坏占位符并让pdo完成工作

$inArray = array_fill(0, count($values), '?');
$inExpr = implode(',', $inArray);
$sql = "... WHERE id IN ($inExpr)";

然后只传递$​​值 - pdo会为你做其余的事情