php sqlsrv_query stored procedure with naming parameters

回眸只為那壹抹淺笑 提交于 2019-12-10 23:56:41

问题


Im using php 5.4 with sqlsrv extension and I'm trying to call this sample stored procedure (NorthWind database):

create  PROCEDURE [dbo].[GetCategories] 
@CategoryID int = null
AS
SELECT * from dbo.Categories where CategoryID= IsNull(@CategoryID,CategoryID)

And I'm using this sqlsrv_query syntax:

$sql = "{ call dbo.GetCategories (?)}";
$catID=2;
$params = array($catID);
$stmt = sqlsrv_query( $conn, $sql,$params);

I want to specify parameter name and value in $params, just like this:

$sql = "dbo.GetCategories";
$catID=2;
$params = array("@CategoryID"=>$catID);
$stmt = sqlsrv_query( $conn, $sql,$params);

It return this error: String keys are not allowed in parameters arrays.

How can i solve this problem? Thanks


回答1:


I found this solution using PDO:

$dbh = new PDO('sqlsrv:server= ...');
$sql = "{CALL dbo.GetCategories (@CategoryID=:CategoryID)}";
$stmt = $dbh ->prepare($sql);

$stmt->bindParam('CategoryID', $catID, PDO::PARAM_INT);

$stmt->execute();

$results = array();
do {
    $results []= $stmt->fetchAll();
} while ($stmt->nextRowset());

echo '<pre>';


echo($results[0][0]['CategoryID'] . ', '.
         $results[0][0]['CategoryName'] . ', '.
         $results[0][0]['Description']);
echo '</pre>';

$stmt->closeCursor();
unset($stmt);



回答2:


You can't use associative arrays for binding values to SQL parameters. The elements in the array must be in the same order as the parameters.



来源:https://stackoverflow.com/questions/13274261/php-sqlsrv-query-stored-procedure-with-naming-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!