简体   繁体   English

在MS SQL Server中使用sqlsrv_execute进行sqlsrv_fetch

[英]sqlsrv_fetch with sqlsrv_execute in MS SQL server

I am trying to extract data from procedure stored on a remote MSSQL server. 我正在尝试从存储在远程MSSQL服务器上的过程中提取数据。 PHP documentation says in sqlsrv_fetch($stmt) , $stmt refers to the resource returned by the sqlsrv_query() or sqlsrv_execute() . PHP文档sqlsrv_fetch($stmt)$stmt指的是sqlsrv_query()sqlsrv_execute()返回的资源。

Here is my code snippet -> 这是我的代码段->

$sql = "exec USP_ABC_ABC_REPORT 'Apple','06/01/2014','10/29/2014','H','A'";

        $segment ='apple';
        $start_date='06/01/2014';
        $end_date ='10/29/2014';
        $something2 ='H';
        $something3 ='A';       

        $abc = sqlsrv_prepare($conn, $sql, array( &$segment, &$start_date, &$end_date, &$something2, &$something3));


        if( $abcd = sqlsrv_execute( $abc)){
                 if(sqlsrv_fetch($abcd)){
                    $id = sqlsrv_get_field( $abcd, 0);
                    echo $id;
            }   else{
                    echo "fetch failed";
                }
        }

This snippet shows an error: 此代码段显示错误:

sqlsrv_fetch() expects parameter 1 to be resource, boolean given. sqlsrv_fetch()期望参数1为资源(给定布尔值)。

sqlsrv_fetch() works fine if I use sqlsrv_query() instead of sqlsrv_execute/prepare. 如果我使用sqlsrv_query()而不是sqlsrv_execute / prepare,则sqlsrv_fetch()可以正常工作。 The possible reason is that sqlsrv_query() returns mixed output instead of boolean. 可能的原因是sqlsrv_query()返回混合输出而不是布尔值。

Could anyone help with using sqlsrv_fetch with execute. 任何人都可以帮助将sqlsrv_fetch与execute配合使用。

sqlsrv_execute returns a boolean indicating success or failure. sqlsrv_execute返回一个布尔值,指示成功或失败。

If the call to sqlsrv_prepare is successful, it returns a statement resource. 如果对sqlsrv_prepare的调用成功,它将返回一个语句资源。 So you can just pass $abc as a parameter of sqlsrv_fetch and sqlsrv_get_field : 因此,您只需传递$abc作为sqlsrv_fetchsqlsrv_get_field的参数sqlsrv_get_field

if (sqlsrv_fetch($abc)){
    $id = sqlsrv_get_field($abc, 0);
    echo $id;
}

Your insights about the cause are correct. 您对原因的见解是正确的。 Check the documentation for sqlsrv_execute and each of the functions. 检查有关sqlsrv_execute和每个功能的文档。

sqlsrv_execute returns either true or false , ( boolean ). sqlsrv_execute返回truefalse布尔值 )。 And this is not what fetch is expecting as input. 而这并不是fetch期望的输入。

Once you undestand the need of matching types of expected parameters on each function you will be able to get along easier with any sort of code. 一旦您不了解在每个函数上都需要匹配期望参数类型的需求,您将能够与任何类型的代码轻松相处。

while into a develpment environment, try to var_dump($abcd); 在开发环境中时,请尝试var_dump($abcd); just after assigning to see its value. 分配后即可查看其值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM