PDO equivalent of mysql_num_rows or mssql_num_rows

允我心安 提交于 2019-11-28 02:13:40

If you want to count the rows you can do this with PDO:

$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);

There is no way to directly count rows when using a SELECT statement with PDO.

So with everyone's help this is what I built.

function getRowsAffected() {

    $rawStatement = explode(" ", $this->query);
    $statement = strtoupper($rawStatement[0]);

    if ($statement == 'SELECT' || $statement == 'SHOW') {

        $countQuery = preg_replace('/(SELECT|SHOW)(.*)FROM/i', "SELECT count(*) FROM", $this->query);
        $countsth = $this->pdo->prepare($countQuery);

        if ($countsth->execute()) {
            $this->rowsaffected = $countsth->fetchColumn();
        } else {
            $this->rowsaffected = 0;
        }
    }

    return $this->rowsaffected;
}

$this->rowsaffected is already being updated in the execute phase if the statement is an INSERT, UPDATE, or DELETE with $sth->rowCount() so I only needed to run this second query on SELECT and SHOWS.

if ($statement == 'INSERT' ||  $statement == 'UPDATE' || $statement == 'DELETE') {
    $this->rowsaffected = $this->sth->rowCount();
}

I feel bad though, because just as I mentioned in my question, that I was looking for an overall solution I seem to have stumbled onto a specific solution that works for me since the code already asks for the number of rows using a function. If the code was doing this:

if (mysql_num_rows($result) > 0) {

then this solution would still create work updating all instances to use that custom function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!