简体   繁体   English

PHP SQLSRV PDO结果数

[英]PHP SQLSRV PDO number of results

Having issues returning number of results in PHP SQLSRV PDO connection, when I try $stmt->rowCount(); 当我尝试$ stmt-> rowCount()时,在PHP SQLSRV PDO连接中返回结果数有问题。 get -1 result, really don't get it. 得到-1结果,真的不明白。

...
...
...
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: 如果要在不单独查询的情况下对行进行计数,则可以使用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 . 对所有数据库驱动程序使用带有PDO的SELECT语句时,无法直接对行进行计数。 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. 小鲍比说, 您的脚本有遭受SQL注入攻击的危险。 . Even escaping the string is not safe! 即使转义字符串也不安全! Learn about prepared statements for PDO . 了解有关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. 您可以使用sqlsrv驱动程序的PDO版本获得select查询的行数,但是,像驱动程序的标准版本(非PDO)一样,您必须指定可滚动游标。 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 . 使用的默认光标是PDO::CURSOR_FWDONLY ,当使用rowCount()时,它返回-1

Microsoft documentation . Microsoft文档

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

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