Skip to content
Advertisement

PHP sqlsrv PDOStatement::rowCount

I have a problem with the rowCount() in this code:

JavaScript

It will print -1, but the fecth is working and rows are returned, so the rest of the code is working fine, it’s only the rowCount() and I don’t understand why.

Thank you

Advertisement

Answer

I assume that you are using PHP Driver for SQL Server (based on the question’s title and the link in the comments) and it seems that you need the PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED option in the PDO::prepare() call.

This is briefly explained in the documentation: You can request a client-side cursor by using PDO::prepare, specifying the PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL cursor type, and then specifying PDO::SQLSRV_ATTR_CURSOR_SCROLL_TYPE => PDO::SQLSRV_CURSOR_BUFFERED.

I’m able to reproduce (and solve) this unexpected behaviour using the following code (based on the code in the question):

JavaScript

One important note – always use parameters in your statement to prevent possible SQL injection issues:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement