将params传递给存储过程

时间:2015-12-31 16:28:17

标签: php sql-server stored-procedures pdo

我收到了以下错误

  

SQLSTATE [42000]:[Microsoft] [SQL Server的ODBC驱动程序11] [SQL Server]必须将参数号44和后续参数传递为' @name = value'。表格' @name = value'已使用,所有后续参数必须以“@name = value'”的形式传递。

这是我的代码

$pdowin->beginTransaction();
    try {
        // headers
        $rows = $pdo->query("SELECT * FROM orders WHERE status = 2 AND productId IS NOT NULL GROUP BY id");
        // fetch the rows
        while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
            $pdowin->query("EXEC sp_salesorderimport
                @salesordernumberid = ".$row['id'].",
                    ... // number of other params here
                ");

            // items
            $items = $pdo->query("SELECT * FROM orders WHERE id = " . $row['id'] . " ORDER BY name ASC");
            while ($item = $items->fetch()) {
                $pdowin->query("EXEC sp_salesorderrowimport
                    @salesordernumberid = ".$row['id'].",
                    @articleid = ".$item['artid'].",
                        ... // number of other params here
                    ");
            }
        }

        $pdowin->commit();
        echo "OK";
    } catch (PDOException $e) {
        $pdowin->rollback();
        echo "ERROR: ".$e;
    }

如果我单独执行这些查询,则所有查询都有效。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

你应该准备你的陈述:

$pdowin->beginTransaction();
    try {
        // headers
        $rows = $pdo->query("SELECT * FROM orders WHERE status = 2 AND productId IS NOT NULL GROUP BY id");

        $stmt = $pdowin->prepare("EXEC sp_salesorderimport
                @salesordernumberid = :saleId,
                    ... // number of other params here
                ");
        // fetch the rows
        while ($row = $rows->fetch(PDO::FETCH_ASSOC)) {
            $stmt->bindValue(':saleId',$row['id']);
            $stmt->execute();

它不仅可以防止SQL注入,还可以避免引号错误和转义字符

相关问题