PHP sqlsrv PDOStatement::rowCount

PHP sqlsrv PDOStatement::rowCount

我对这段代码中的 rowCount() 有疑问:

$sqlLoc= "
          DECLARE @Data2 AS DATE; 
          SET @Data2 = CONVERT(DATE,CONVERT(date, '$dataFine'), 102);
          
          DECLARE @Data1 AS DATE;
          SET @Data1 = CONVERT(DATE,CONVERT(date, '$dataInizio'), 102);
          
          SELECT noteincassi.CodLocale,Insegna,Citta
          FROM [Edera].[dbo].[NoteIncassi]
          JOIN edera.dbo.AnagraficaLocali ON AnagraficaLocali.CodLocale=NoteIncassi.CodLocale
          WHERE DataIncasso >= @Data1  AND DataIncasso <= @Data2 AND tipoincasso = '6' AND sospeso = 0
          GROUP BY noteincassi.CodLocale,insegna,Citta
          ORDER BY Insegna";
$queryLoc = $conn->prepare($sqlLoc,array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$queryLoc->execute();

echo $numero=$queryLoc->rowCount();

echo "<h1>MEDIA INCASSI DAL ".date('d-m-Y',strtotime($dataInizio))." AL ".date('d-m-Y',strtotime($dataFine))."</h1>";

$id=0;
while($resultLoc=$queryLoc->fetch()){

它会打印 -1,但 fecth 正在运行并返回行,所以其余代码运行良好,只有 rowCount(),我不明白为什么。

谢谢

我假设您正在为 SQL 服务器使用 PHP Driver(基于问题的标题和评论中的 link),看来您在 PDO::prepare() 调用中需要 PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED 选项。

这在 documentation 中有简要说明:您可以使用 PDO::prepare 请求 client-side 游标,指定 PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL 游标类型,然后指定 PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED.

我能够使用以下代码(基于问题中的代码)重现(并解决)这种意外行为:

$sql = "
    DECLARE @Data2 AS DATE; 
    SET @Data2 = GETDATE();
    
    DECLARE @Data1 AS DATE;
    SET @Data1 = GETDATE();

    SELECT A, B
    FROM (VALUES (11, 22), (33, 44)) v (A, B)
";
$statement = $conn->prepare(
    $sql, 
    array(
        PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, 
        PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED
    )
);
$statement->execute();
echo $numero = $statement->rowCount();

重要说明 - 始终在语句中使用参数以防止可能的 SQL 注入问题:

<?php

... 
$sqlLoc = "
    DECLARE @Data2 AS DATE; 
    SET @Data2 = CONVERT(DATE, CONVERT(date, :dataFine), 102);
    
    DECLARE @Data1 AS DATE;
    SET @Data1 = CONVERT(DATE, CONVERT(date, :dataInizio), 102);
    
    SELECT noteincassi.CodLocale, Insegna,Citta
    FROM [Edera].[dbo].[NoteIncassi]
    JOIN edera.dbo.AnagraficaLocali ON AnagraficaLocali.CodLocale=NoteIncassi.CodLocale
    WHERE DataIncasso >= @Data1  AND DataIncasso <= @Data2 AND tipoincasso = '6' AND sospeso = 0
    GROUP BY noteincassi.CodLocale,insegna,Citta
    ORDER BY Insegna
";
$statement = $conn->prepare(
   $sql, 
   array(
      PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL, 
      PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED
   )
);
$queryLoc->bindParam(':dataFine', $dataFine);
$queryLoc->bindParam(':dataInizio', $dataInizio);
$queryLoc->execute();   
...

?>