Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDOStatement::rowCount result when used after PDO::commit?

In the MySQL docs, there is a note about using mysql_affected_rows after a transaction commit: http://php.net/manual/en/function.mysql-affected-rows.php

Note: Transactions
If you are using transactions, you need to call mysql_affected_rows() after your INSERT, UPDATE, or DELETE query, not after the COMMIT.

However, there is no such note on the PDOStatement::rowCount doc: http://www.php.net/manual/en/pdostatement.rowcount.php

Does this mean the commit will not affect the affected rows count after INSERT, UPDATE or DELETE queries when using the PDO object?

like image 474
Ozzy Avatar asked Apr 22 '12 21:04

Ozzy


People also ask

How to get row count in php PDO?

PDOStatement::rowCount() returns the number of rows affected by a DELETE, INSERT, or UPDATE statement. print("Return number of rows that were deleted:\n"); $count = $del->rowCount(); print("Deleted $count rows.

How to use row count in php?

The mysqli_num_rows() function is an inbuilt function in PHP which is used to return the number of rows present in the result set. It is generally used to check if data is present in the database or not. To use this function, it is mandatory to first set up the connection with the MySQL database.

What is PDOStatement?

PDOStatement::execute — Executes a prepared statement. PDOStatement::fetch — Fetches the next row from a result set. PDOStatement::fetchAll — Fetches the remaining rows from a result set. PDOStatement::fetchColumn — Returns a single column from the next row of a result set.

What is a PDO statement?

The PDO represents a connection between PHP and a database server. The PDOStatement represents a prepared statement and, after the statement is executed, an associated result set. The PDOException represents an error raised by PDO.


1 Answers

A PDOStatement is returned for each query that is executed. You will be able to use PDOStatement->rowCount() at any time in your code (during or after a transaction and rollback/commit doesn't matter). Each object takes care of maintaining itself.

The reason mysql_affected_rows has that transaction note is because it is only aware of a single mysql connection resource. This means that when you complete the transaction (commit/rollback) a new query has been sent to the DB, thus altering which result is being processed for the number of affected rows.

like image 153
Nate Avatar answered Sep 23 '22 18:09

Nate