Row count with PDO

前端 未结 23 3235
春和景丽
春和景丽 2020-11-21 22:57

There are many conflicting statements around. What is the best way to get the row count using PDO in PHP? Before using PDO, I just simply used mysql_num_rows.

23条回答
  •  星月不相逢
    2020-11-21 23:35

    Here's a custom-made extension of the PDO class, with a helper function to retrieve the number of rows included by the last query's "WHERE" criteria.

    You may need to add more 'handlers', though, depending on what commands you use. Right now it only works for queries that use "FROM " or "UPDATE ".

    class PDO_V extends PDO
    {
        private $lastQuery = null;
    
        public function query($query)
        {
            $this->lastQuery = $query;    
            return parent::query($query);
        }
        public function getLastQueryRowCount()
        {
            $lastQuery = $this->lastQuery;
            $commandBeforeTableName = null;
            if (strpos($lastQuery, 'FROM') !== false)
                $commandBeforeTableName = 'FROM';
            if (strpos($lastQuery, 'UPDATE') !== false)
                $commandBeforeTableName = 'UPDATE';
    
            $after = substr($lastQuery, strpos($lastQuery, $commandBeforeTableName) + (strlen($commandBeforeTableName) + 1));
            $table = substr($after, 0, strpos($after, ' '));
    
            $wherePart = substr($lastQuery, strpos($lastQuery, 'WHERE'));
    
            $result = parent::query("SELECT COUNT(*) FROM $table " . $wherePart);
            if ($result == null)
                return 0;
            return $result->fetchColumn();
        }
    }
    

提交回复
热议问题