在PHP中使用PDO类获取num_rows时出现问题 [英] problem getting num_rows with PDO class in php

查看:255
本文介绍了在PHP中使用PDO类获取num_rows时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚更改了数据库连接.我还不习惯PDO类或OOP.无论如何,我这样连接到数据库:

I have just changed my database connection. I am not used to the PDO class or OOP yet. Anyway, I connect to the db like this:

        $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
        try
        {
            $this->db = new PDO($dsn, DB_USER, DB_PASS);
        }
        catch ( Exception $e )
        {
            die ( $e->getMessage() );
        }

我正在尝试从此查询中获取行数:

I am trying to get number of rows from this query:

    $ip = $this->ip(); 
    $sql = "SELECT `id` FROM `login_failed`
            WHERE `ip` = :ip AND `time` BETWEEN NOW( ) - INTERVAL 120 MINUTE AND NOW( )
            LIMIT 3";
    try 
    {
        $stmt = $this->db->prepare($sql);
        $stmt->bindParam(':ip', $ip, PDO::PARAM_STR);
        $result = $stmt->execute(); // $result = true
        $n = $stmt->num_rows ; // n = NULL?
        $stmt->closeCursor(); 
    }       
    catch (Exception $e)
    {
        die ($e->getMessage() ); 
    }

phpmyadmin中,我得到一个结果,所以我的查询是正确的,但是由于某些原因,$nNULL.如何使用PDO

In phpmyadmin I get a result so my query is correct, but $n is NULL for some reason.. How do I get number of rows with PDO

推荐答案

$stmt的类型为 PDOStatement .该类没有num_rows属性.

您可能正在寻找 rowCount ,但是该状态的文档:

You might be looking for rowCount instead, but the documentation for that states:

如果最后一条SQL语句由执行 相关的PDOStatement是一个 SELECT语句,某些数据库可能 返回返回的行数 那句话.但是这个 行为并不能完全保证 数据库,不应该依赖 用于便携式应用.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

如果是这样的话,如果要实际SELECT所有数据,则可以通过遍历结果集来可靠地确定返回了多少行(或者只需调用

The long and the short if it is that, if you want to actually SELECT all that data, you can reliably determine how many rows were returned by iterating over the result set (or just call fetchAll and count the items in the array). If you don't need the data but just a number, use SELECT COUNT instead.

因此,要在不更改查询的情况下对行进行计数:

So, to count the rows without changing the query:

$result = $stmt->execute();
$rows = $stmt->fetchAll(); // assuming $result == true
$n = count($rows);

这篇关于在PHP中使用PDO类获取num_rows时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆