Question:
Reworking a PHP application to use PDO, developers may encounter the need to replicate the functionality of mysql_num_rows for counting the number of rows in a result set. How can this be achieved using PDO?
Answer:
PDO provides two methods to count rows:
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $num_rows = $res->fetchColumn();</code>
<code class="php">$res = $DB->prepare('SELECT COUNT(*) FROM table'); $res->execute(); $num_rows = $res->fetchColumn();</code>
In addition to row counting, these methods can be used to check for data existence:
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $data_exists = ($res->fetchColumn() > 0) ? true : false;</code>
To determine if there is only one row in a table, the following code can be used:
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');</code>
The above is the detailed content of How to Replicate mysql_num_rows Functionality Using PDO?. For more information, please follow other related articles on the PHP Chinese website!