2014-01-18 93 views
1

我有以下几点:阵列中选择查询

<?php 

    $array = join(',', $ids); // this prints 3,4,6,7,8 

    $stmt = $cxn->prepare('SELECT * FROM comments WHERE id IN (?)'); 
    $stmt->bind_param('i', $array); 
    $stmt->execute(); 

?> 

然而,当我把它打印结果,那只能说明从第一个ID(3)的意见,而不是其他人。怎么了?

+0

在'IN'条款每个元素都是一个独立的元素,而不是 –

+0

你传递一个字符串到查询,但告诉查询期待一个整数(在'i'在'bind_param一个巨大的字符串()')。将'i'改为's',它应该可以工作。 – jedwards

+0

@jedwards没有工作。 – Bagwell

回答

-1

将它们绑定到一个字符串。

$idString = ''; 
foreach($ids as $id) { 
$idString .= $id . ','; 
} 
$idString = substr($idString, 0, -1); 
$stmt = $cxn->prepare('SELECT * FROM comments WHERE id IN (?)'); 
$stmt->bind_param('s', $idString); 
$stmt->execute(); 
+0

你真的尝试过吗? –

+0

是吗?有用。为什么downvote? – Mave

+2

因为它不应该工作....你正在创建包含“3,4,6,7,8”的字符串,并试图将其绑定为一个整数 –

1

我相信这工作打算,你必须直接替换值到字符串:

$idString = ''; 
foreach($ids as $id) { 
$idString .= $id . ','; 
} 
$idString = substr($idString, 0, -1); 
$stmt = $cxn->prepare("SELECT * FROM comments WHERE id IN (".$idstring.")"); 
$stmt->execute(); 

不幸的是,这可以再打开你到SQL注入攻击。

+0

任何方式来做到这一点,同时避免漏洞? – Bagwell

+0

@Bagwell,当然,最简单的方法是验证/转义'$ ids' - 一个更复杂的方法是在知道'$ ids'的长度后构建你传递的字符串,并包含很多'?'符号,然后相应地构建'bind_param()'函数参数。 – jedwards

0
$arrayCount = count($ids); 
$binders = array_fill(0, $arrayCount, '?'); 

// Create an array of references to the values we want to bind 
$bindValues = array(); 
foreach($ids as $key => $id) 
    $bindValues[$keys] = &$ids[$key]; 

// Build SQL statement with the necessary number of bind placeholders 
$stmt = $cxn->prepare(
    'SELECT * FROM comments WHERE id IN (' . implode(',', $binders) . ')' 
); 
// Bind each value (has to be done by reference) 
call_user_func_array(array($stmt, "bind_param"), $bindValues)); 
$stmt->execute();