dacami
dacami

Reputation: 75

Executing a Stored Procedure with pdo_sqlsrv

I'm trying to figure out how do execute a stored procedure with php5.3/pdo_sqlsrv on sql server 2008.

I've found this code:

$sql = new PDO( "sqlsrv:server=$server;Database = $database", $user, $password);
$query = "{? = CALL sp_Login(?, ?)}"; 
$stmt = $sql->prepare( $query ); 
$returnVariable = 0;
$inputVariable1 = 'input1';
$inputVariable2 = 'input2';
$stmt->bindParam(1,$returnVariable,PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,100);
$stmt->bindParam(2,$inputVariable1,PDO::PARAM_STR);
$stmt->bindParam(3,$inputVariable2,PDO::PARAM_STR);
$stmt->execute();
echo "Return value: ".$returnVariable;

the stored procedure has two input and one output paramter, but it seems it returns nothing, return value is still 0..

I can run select/insert queries, so it's not the connection.

Is there any good documentation about stored procedures with pdo_sqlsrv?

thanks!

Upvotes: 1

Views: 7160

Answers (3)

Yianni A
Yianni A

Reputation: 21

Your stored proc needed the "SET NOCOUNT ON" statement included so that the Insert statement within didn't require you to call the nextRowset() method.

Upvotes: 1

dacami
dacami

Reputation: 75

after a day of search i found a way of calling the sp... the problem was that the stored procedure was running a insert query and i had to call nextRowset() to get the return value

http://social.msdn.microsoft.com/Forums/en/sqldriverforphp/thread/55f21fc5-dbc0-4fe4-a4ae-f15905a4293a

$sql = new PDO( "sqlsrv:server=$server;Database = $database", $user, $password);

$input1 = "input1";
$input2 = "input2";
$return_value = -1;

$proc = '{? = CALL sp_Name (?, ?) }';
$stmt = $sql->prepare( $proc );
$stmt->bindParam(1,$return_value ,PDO::PARAM_INT|PDO::PARAM_INPUT_OUTPUT,4);
$stmt->bindParam(2,$input1,PDO::PARAM_STR);
$stmt->bindParam(3,$input2,PDO::PARAM_STR);

$stmt->nextRowset(); //skip INSERT result

$result = $stmt->fetch(PDO::FETCH_ASSOC);
/* Display the value of the output parameter  */
echo "Return value: ".$return_value.'<br>';

Upvotes: 3

tonymarschall
tonymarschall

Reputation: 3882

Maybe this form the manual is helpful

  // Example #4 Calling a stored procedure with an output parameter

  $stmt = $dbh->prepare("CALL sp_returns_string(?)");
  $stmt->bindParam(1, $return_value, PDO::PARAM_STR, 4000); 

  $stmt->execute();

  print "procedure returned $return_value\n";


  // Example #5 Calling a stored procedure with an input/output parameter

  $stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
  $value = 'hello';
  $stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); 

  $stmt->execute();

  print "procedure returned $value\n";

Upvotes: 0

Related Questions