PDO将数组传递给存储过程

时间:2015-05-18 08:14:08

标签: php arrays pdo

如何将数组传递到:

$query = 'CALL myStoredProcedure(:array)'

在该存储过程的IN子句中使用它吗?

BTW:它不重复。将数组传递给存储过程并不等于直接将数组传递给SELECT查询。所以复制标记是错误的。我可以将数组作为一组(?,?,?,?,?)传递,但是如何在IN子句中调用未知的参数计数?

$params = array(1, 21, 63, 171);
$place_holders = implode(',', array_fill(0, count($params), '?'));
$sth = $dbh->prepare("SELECT id, name FROM contacts WHERE id IN ($place_holders)");
$sth->execute($params);

2 个答案:

答案 0 :(得分:1)

<强>解决!

<强> PHP:

$params = implode(',', $array);//string arrays should escape each element with quotes
$stmt = $db->prepare('CALL myProcedure(:array)');
$stmt->bindParam(':array', $params, PDO::PARAM_STR);

存储过程:

CREATE PROCEDURE `myProcedure`(IN `array` VARCHAR(2048))
#VARCHAR(2048) - maximum expected total length of imploded array
BEGIN
SET @query:= CONCAT(
'SELECT
    *
FROM
    `some` AS `table`
WHERE
    `table`.`field` IN (',`array`,')');
PREPARE stmt FROM @query;
EXECUTE stmt;
END

答案 1 :(得分:0)

你不能传递数组在mysql中使用,做类似

的事情
$array  = implode(',',$array);

$query  = "CALL myStoredProcedure($array)";

根据我的经验,SELECT * FROM table1 WHERE column IN(?)之类的查询不起作用,您必须将IN值直接放在查询中