Finding an Alternative for mysql_num_rows with PDO
In an effort to transition PHP files to use PDO, developers may face a dilemma regarding the alternative to the deprecated mysql_num_rows function. Originally, using mysql_num_rows, it was possible to count rows returned from a MySQL query and perform conditional actions.
PDO Equivalent for Counting Rows
The PDO equivalent for counting rows is to utilize the fetchColumn() method. This method can be used in conjunction with a query() or prepare() and execute() statement.
Using query() and fetchColumn()
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $num_rows = $res->fetchColumn();</code>
Using prepare(), execute(), and fetchColumn()
<code class="php">$res = $DB->prepare('SELECT COUNT(*) FROM table'); $res->execute(); $num_rows = $res->fetchColumn();</code>
Conditional Statements with fetchColumn()
The fetchColumn() method can also be used to conditionally determine if data exists or has been selected:
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $data_exists = ($res->fetchColumn() > 0) ? true : false;</code>
Incorporating Conditional Variables
By incorporating variables, you can directly assign the result of a row count check:
<code class="php">$res = $DB->query('SELECT COUNT(*) FROM table'); $message = ($res->fetchColumn() > 0) ? array('status' => 'ok') : array('status' => 'error');</code>
By utilizing the PDO fetchColumn() method, developers can effectively replace the functionality of mysql_num_rows in their PHP scripts when transitioning to PDO for database operations. This ensures compatibility with modern PHP environments and best practices for database interactions.
The above is the detailed content of How to Use PDO to Count Rows and Replace mysql_num_rows?. For more information, please follow other related articles on the PHP Chinese website!