I am trying to execute a stored procedure which inputs data to my database.
I am setting up my parameters as follows:
($conn has my db creds, $xml contains data from an XML file)
$params = array(
array($xml->filenumber, SQLSRV_PARAM_IN, SQLSRV_SQLTYPE_VARCHAR(20)),
array($xml->lastName, SQLSRV_PARAM_IN, SQLSRV_SQLTYPE_VARCHAR(25)),
array($xml->firstName, SQLSRV_PARAM_IN, SQLSRV_SQLTYPE_VARCHAR(25)),
array("", SQLSRV_PARAM_OUT, SQLSRV_PHPTYPE_STRING(14))
);
The datatypes correspond with the sproc:
@FileNumber varchar(20),
@FamilyName varchar(25),
@GivenName varchar(25),
@FileID varchar(14) output
And then executing it in PHP :
$sql = "EXEC dbo.AddFileHdr @FileNumber = ?, @FamilyName = ?, @GivenName = ?, @FileID =?";
$stmt = sqlsrv_prepare($conn, $sql, $params);
if( !$stmt ) {
die( print_r( sqlsrv_errors(), true));
}
if(sqlsrv_execute($stmt)){
while($res = sqlsrv_next_result($stmt)){
//doesnt need to output anything here
}
}else{
die( print_r( sqlsrv_errors(), true));
}
Expected behavior is for the query to return a 14 character varchar FileID
after I insert the 3 fields. I have tested the sproc in SQL Studio and it works fine.
2
Answers
Turns out the issue was because I was not passing a string to the parameter with
$xml->child
This was solved by casting the xml data as a string e.g.:
$param2 = (string)$xml->lastName;
SQLSRV_PHPTYPE_STRING
accepts an encoding type constant as parameter:You can change
SQLSRV_ENC_CHAR
with other encoding constants as stated here: https://www.php.net/manual/en/sqlsrv.constants.phpBy the way, i suggest you to always use variables for your query parameters and pass it by reference (see
$fileId
):