简体   繁体   中英

PHP SQLSRV PDO number of results

Having issues returning number of results in PHP SQLSRV PDO connection, when I try $stmt->rowCount(); get -1 result, really don't get it.

...
...
...
if(empty($region)){
    $query2 = "SELECT [QuotID], [QuotNumber], CreationDate, QuotDate
    FROM [dbo].[vQuotaion]
    GROUP BY [QuotID]
        ,[QuotNumber]
        ,[CreationDate]
        ,[QuotDate]
    HAVING CreationDate >='".$fdate."' AND CreationDate <='".$edate."' AND  ProType = 'OPSFi' ORDER BY CreationDate DESC";
    $stmt2 = $conn->query( $query2 );           
} else {
    ...
    ...
    ...
}
...
...
...
<?php
if(empty($stmt2)){
    echo '';
    }else{
        while ($result = $stmt2->fetch(PDO::FETCH_ASSOC)){
        bla bla bla;
    }
}
?>

If you want to count the rows without a separate query you can do this with PDO:

$rows = $stmt2->fetchAll();
$num_rows = count($rows);

There is no way to directly count rows when using a SELECT statement with PDO for all database drivers . You could create a function using the code above if you need to retrieve counts regularly.

Warning!

Little Bobby says your script is at risk for SQL Injection Attacks. . Even escaping the string is not safe! Learn about prepared statements for PDO .

You can get the row count of a select query with the PDO versions of the sqlsrv drivers however, like the standard version of the drivers (non-PDO), you have to specify a scrollable cursor. Like so:

$query = "SELECT * FROM myTable";
$stmt = $conn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$rows = $stmt->rowCount();

The default cursor used is PDO::CURSOR_FWDONLY which, when rowCount() is used, returns -1 .

Microsoft documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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