我尝试使用PHP运行MSSQL存储过程,然后获取结果并将它们回显到页面。结果输出为两列不同的记录集。请参阅screenshot。
我修改了一些变量名称和输出以保护一些敏感信息,但下面的SQL代码正是我在MSSQL Server Management Studio中运行的,它返回上面链接的输出屏幕截图。
我还通过PHP尝试了以下操作,但没有返回任何结果:
if (!@mssql_connect($host,$username,$password)) {
$error = $db_connect_error;
echo $error;
}
@mssql_select_db($dbname);
$stmt=mssql_init("[dbo].[stored_procedure_name]");
mssql_bind($stmt, "@StartTime", $start_last, SQLVARCHAR, FALSE);
mssql_bind($stmt, "@EndTime", $end_last, SQLVARCHAR, FALSE);
mssql_bind...continued for all variables
$result = mssql_execute($stmt);
$arr = mssql_fetch_row($result);
print_r($arr);
我尝试过通过谷歌搜索找到的其他几种不同的方法,以便在PHP中回显数据或将数据保存到数组中,但我尝试过的任何方法都无效。
在MSSQL Server Management Studio中运行没有问题的MSSQL语句,当我找到存储过程并从MSSQL SMS运行它时,这是默认格式:
DECLARE @RC int
DECLARE @StartTime datetime
DECLARE @EndTime datetime
DECLARE @a varchar(4000)
DECLARE @b varchar(4000)
DECLARE @c varchar(50)
DECLARE @d varchar(50)
DECLARE @e varchar(50)
DECLARE @f varchar(50)
DECLARE @g int
DECLARE @h int
DECLARE @i int
DECLARE @j int
DECLARE @k int
DECLARE @l int
DECLARE @m int
DECLARE @n int
DECLARE @o int
DECLARE @p int
DECLARE @q int
DECLARE @r varchar(100)
DECLARE @s int
DECLARE @t float
DECLARE @u float
DECLARE @v float
DECLARE @w int
-- TODO: Set parameter values here.
SET @StartTime = '2017-02-01 07:30'
SET @EndTime = '2017-02-01 19:30'
SET @a = 'string'
SET @b = 'string'
SET @c = 'string'
SET @d = 'string'
SET @e = 'string'
SET @f = 'string'
SET @g = 105
SET @h = 108
SET @i = 101
SET @j = 147
SET @k = 124
SET @l = 141
SET @m = 103
SET @n = 186
SET @o = 185
SET @p = 113
SET @q = 182
SET @r = 'string'
SET @s = 77
SET @t = 101.5
SET @u = 1000
SET @v = 25.4
SET @w = 1
EXECUTE @RC = [dbo].[spLocal_RptCvtgLinestatus]
@StartTime
,@EndTime
,@a
,@b
,@c
,@d
,@e
,@f
,@g
,@h
,@i
,@j
,@k
,@l
,@m
,@n
,@o
,@p
,@q
,@r
,@s
,@t
,@u
,@v
,@w
答案 0 :(得分:0)
首先,我的评论提到您应该考虑更新为mysqli_*
或PDO
。
对于您当前的设置,您错过了它看起来像
的连接$connection = mssql_connect($servername, $username, $password);
//Select a db
mssql_select_db('your_db_name', $connection);
//Use the connection. I do not think you need to fully qualify the sproc name.
$stmt = mssql_init('stored_procedure_name', $connection);
此外,在执行mssql_fetch_row时,它只返回一行,因此您需要循环它:
$data = array();
while ($row = mssql_fetch_row($result)){
$data[] = $row;
}
print_r($data);
答案 1 :(得分:0)
要遍历多个记录集,您可以尝试此操作。
$sql = "EXEC spr_MyStoredProcedure @param1 = 6, @param2 = 5;";
$conn = sqlsrv_connect( $hostname, array( "Database"=>$database, "UID"=>$username, "PWD"=>$password ));
if( !$conn) {
die( print_r( sqlsrv_errors(), true));
}
$result = sqlsrv_query($conn, $sql, null);
if($result ) {
while( $obj = sqlsrv_fetch_object($result)){ // check the first recordset
print_r($obj);
}
while( sqlsrv_next_result($result)){ // if there are any more recordsets
while( $obj = sqlsrv_fetch_object($result)){ // loop them too
print_r($obj);
}
}
}
sqlsrv_free_stmt( $result );
sqlsrv_close( $conn );
此产品尚未在生产环境中经过测试,因此您的行驶里程可能会有所不同。