-6ren">
gpt4 book ai didi

php - Doctrine - 如何将数组绑定(bind)到 SQL?

转载 作者:行者123 更新时间:2023-12-03 00:04:43 25 4
gpt4 key购买 nike

我的 SQL 看起来像这样:

$sql = "select * from user where id in (:userId) and status = :status";

$em = $this->getEntityManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindValue(':userId', $accounts, \Doctrine\DBAL\Connection::PARAM_INT_ARRAY);
$stmt->bindValue(':status', 'declined');
$stmt->execute();

$result = $stmt->fetchAll();

但它返回:

An exception occurred while executing (...)

with params [[1,2,3,4,5,6,7,8,11,12,13,14], "declined"]

Notice: Array to string conversion

我无法使用queryBuilder,因为我的真实 SQL 更复杂(例如包含连接选择、联合等)

最佳答案

您不能将准备好的语句与数组一起使用,因为 sql 本身不支持数组。这真是一个耻辱。在此过程中,您实际上需要确定数据是否包含三个项目并发出 IN (?,?,?)。 Doctrine ORM 实体管理器会自动为您完成此操作。

幸运的是,DBAL 可以满足您的需求。您只是不使用绑定(bind)或准备。该手册有一个示例:https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#list-of-parameters-conversion

在你的情况下,它看起来像:

$sql = "select * from user where id in (?) and status = ?";
$values = [$accounts,'declined'];
$types = [Connection::PARAM_INT_ARRAY, \PDO::PARAM_STR];
$stmt = $conn->executeQuery($sql,$values,$types);
$result = $stmt->fetchAll();

上面的代码未经测试,但您应该明白了。 (确保使用 Doctrine\DBAL\Connection; 作为 Connection::PARAM_INT_ARRAY)

使用命名参数的人注意:

如果您使用命名参数(:param 而不是 ?),则在提供类型时应尊重参数名称。例如:

$sql = "select * from user where id in (:accounts) and status = :status";
$values = ['accounts' => $accounts, 'status' => 'declined'];
$types = ['accounts' => Connection::PARAM_INT_ARRAY, 'status' => \PDO::PARAM_STR];

关于php - Doctrine - 如何将数组绑定(bind)到 SQL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37209686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com