Counting Rows Using PDO
In legacy PHP code, the mysql_num_rows() function was frequently used to count the number of rows returned by a MySQL query. However, with the adoption of PDO (PHP Data Objects), this function is no longer available.
For PDO, there are alternative methods to achieve the same functionality. One option is to use the ->fetchColumn() method:
$res = $DB->query('SELECT COUNT(*) FROM table'); $num_rows = $res->fetchColumn();
Here, $res is the result of a PDO query, and $num_rows will hold the count returned by the query.
Another option is to use a prepared statement:
$res = $DB->prepare('SELECT COUNT(*) FROM table'); $res->execute(); $num_rows = $res->fetchColumn();
Both of these methods effectively emulate the behavior of mysql_num_rows().
You can also use ->fetchColumn() to perform conditional checks, such as determining if data exists:
$res = $DB->query('SELECT COUNT(*) FROM table'); $data_exists = ($res->fetchColumn() > 0) ? true : false;
By employing these techniques, you can seamlessly count rows using PDO, mimicking the functionality of mysql_num_rows().
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3