In some drivers rowCount() only works when using the prepare() with PDO::CURSOR_SCROLL
So, you can modify PDO class:
<?php
class myPDO extends PDO
{
function query($query, $values=null)
{
if($query == "")
return false;
if($sth = $this->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)))
{
$res = ($values) ? $sth->execute($values) : $sth->execute();
if(!$res)
return false;
}
return $sth;
}
}
?>
Now let's test (i using php 5.2.9-2):
<?php
function TestRowCount($dsn, $db_user, $db_pass)
{
$pdh = new PDO($dsn, $db_user, $db_pass);
$sth = $pdh->query("SELECT * FROM sys.tables");
print "rowCount() Standart: ".$sth->rowCount()."<br>";
$pdh = new myPDO($dsn, $db_user, $db_pass);
$sth = $pdh->query("SELECT * FROM sys.tables");
print "rowCount() New: ".$sth->rowCount()."<br><br>";
$pdh=null;
}
$db_server = "xxx";
$db_name = "xxx";
$db_user = "xxx";
$db_pass = "xxx";
print "PDO_MSSQL"."<br>";
TestRowCount("mssql:host=$db_server;dbname=$db_name", $db_user, $db_pass);
print "MSSQL throw PDO_ODBC"."<br>";
TestRowCount("odbc:DRIVER={SQL Server};SERVER=$db_server;DATABASE=$db_name;", $db_user, $db_pass);
print "MS SQL driver 2.0"."<br>";
TestRowCount("sqlsrv:server=$db_server;Database=$db_name", $db_user, $db_pass);
?>
My results:
-------------------
PDO_MSSQL
rowCount() Standart: 0
rowCount() New: 0
MSSQL throw PDO_ODBC
rowCount() Standart: -1
rowCount() New: 53
MS SQL driver 2.0
rowCount() Standart: -1
rowCount() New: 53
-------------------
With myPDO class you can use prepared queries like:
<?php
$pdh = new myPDO($dsn, $db_user, $db_pass);
$sth = $pdh->query("select * from data where id>? or name like ?", array(100, "A%"));
?>