简体   繁体   English

如何使用PDO获取mysql_num_rows?

[英]How to get mysql_num_rows with PDO?

How can I easily get the number of rows returned with " SELECT * " SQL-query? 如何轻松获得通过“ SELECT * ” SQL查询返回的行数?

function valid_credentials($db,$name,$pw) {
    try {

    $sth = $db->prepare("SELECT * FROM ib_members WHERE name=:val AND pw=:val2");
    $sth->bindValue(":val",$name);
    $sth->bindValue(":val2",$pw);   
    $sth->execute();


    $numrows = $sth->fetchColumn();

    return $numrows;

    } catch (PDOException $e) {

        return $e->getMessage();

    }
}

That returns 14, which is definately not the number of rows returned, but it's the ID that the first row has. 返回14,这绝对不是返回的行数,而是第一行的ID。

For DELETE , INSERT , or UPDATE statements, use PDOStatement::rowCount() . 对于DELETEINSERTUPDATE语句,请使用PDOStatement :: rowCount()

For SELECT statements, count the rows manually in your while( $sth->fetch() ) loop (you can break out of the loop if the count exceeds a certain threshold, for instance), or execute a separate query to have the database return the row count (for example, SELECT COUNT(*) FROM table WHERE column = ? ). 对于SELECT语句,请while( $sth->fetch() )循环中手动计数行while( $sth->fetch() )例如,如果计数超过某个阈值,则可以break循环),或者执行单独的查询以获取数据库返回行数(例如, SELECT COUNT(*) FROM table WHERE column = ? )。

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

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