2014-04-06 2 views
1

데이터베이스가 있고 user_ids 배열을 전달하여 동일한 쿼리에서 여러 사용자의 이름을 가져 오려고합니다. 슬프게도, 나는 이것을 작동시킬 수 없다. 매개 변수가 배열입니다mysql 쿼리에 매개 변수로 여러 값 전달하기

$stmt = $this->db->prepare('SELECT name FROM users WHERE user_id=?'); 

:

$stmt->bind_param('i', $user_ids); 

user_ids 배열이 {1, 2}과 같은

나는이 쿼리가 있습니다. 기본적으로 데이터베이스를 한 번 이상 쿼리하지 않고도 사용자 1과 사용자 2의 이름을 얻고 싶습니다. 이 코드가있을 때

, 나는뿐만 아니라 다른 사람, 첫 번째 사용자의 이름을 얻을 수가 :

$stmt->bind_result($name); 
while ($stmt->fetch()) { 
    array_push($names, $name); 
} 

내가 어떻게 $names = array();

같은 $names을 수 초기화 한 점을 명심 나는 이것을 해결합니까?

도움이 될 것입니다.

답변

1

이 같은 IN 문을 사용한다 : 영감

<?php 
//Your array 
$user_ids= array(1, 2); 

$inQuery = implode(',', array_fill(0, count($ids), '?')); 

$db = new PDO(...); 
$stmt = $db->prepare('SELECT name FROM users WHERE user_id IN(' . $inQuery . ')'); 

// bindvalue is 1-indexed, so $k+1 
foreach ($user_ids as $k => $id) 
    $stmt->bindValue(($k+1), $id); 

$stmt->execute(); 


Can I bind an array to an IN() condition?하여 PHP docs

<?php 
/* Execute a prepared statement using an array of values for an IN clause */ 
$params = array(1, 21, 63, 171); 
/* Create a string for the parameter placeholders filled to the number of params */ 
$place_holders = implode(',', array_fill(0, count($params), '?')); 

/* 
    This prepares the statement with enough unnamed placeholders for every value 
    in our $params array. The values of the $params array are then bound to the 
    placeholders in the prepared statement when the statement is executed. 
    This is not the same thing as using PDOStatement::bindParam() since this 
    requires a reference to the variable. PDOStatement::execute() only binds 
    by value instead. 
*/ 
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)"); 
$sth->execute($params); 
?> 
+1

처럼 이것을 사용할 수 있습니다'$ stmt-> ($ user_ids)을 실행;' – naomik

+0

'$ stmt-> execute ($ user_ids)'매개 변수를 바인딩 할 때 **이 오류가 발생합니다 ** mysqli_stmt :: execute()는 정확히 0 개의 매개 변수를 필요로합니다. ** – Aleksander

+0

@Aleplay, 먼저 접근 방식을 시도하고 echo $ inQuery , 넌 봐야 해 "?,?" 2 개의 매개 변수가 예상됨을 선언합니다. – sdespont

1

에서 나는 ?,?,?,? 문자열을 귀찮게하지 않을 것입니다. 시간 낭비라고 생각합니다. 나는 독자적으로 ID의 어레이를 위생 처리하는 재사용 가능한 함수를 만들 것이다.

/** 
* @param int|int[] $id - an id, or array of ids 
* @return string 
*/ 
function in($id) { 
    return implode(
     ",", 
     array_unique(
      array_filter(
       array_map("intval", (array)$id), 
       function($e){ return $e > 0; } 
      ) 
     ) 
    ); 
} 


$a = 1; 
$b = array(1, 2, 3, 1, 1, 1, "foo", "bar", 0, 5, null, -1); 

in($a); // 1 
in($b); // 1,2,3,5 

당신은 그냥 사용할 수 있습니다, 당신은`foreach`으로 PARAMS을 결합 할 필요가 없습니다

$query = $db->prepare("SELECT name FROM users WHERE user_id IN(" . in($user_ids) . ")"); 
관련 문제