The fetch method returns false both if the recordset is empty and if there is an actual error. The method described here allows you to easily recognize what is happening:
ensure that PDO fetch method result "false" is a error or empty result
It works well with pdo_mysql, however pdo_sqlsrv throws an error even when the recordset is empty. Is this the intended behaviour? Is it possible to avoid those errors?
EDIT: the error is "There are no more rows in the active result set" and it is produced when you try to fetch a recordset which is already completely fetched. This not happens with pdo_mysql, which just returns false.
EDIT 2: I have finally understood the problem more in details: the first time you fetch an empty recordset you get FALSE, then, if you fetch again, you get an error. This doesn't happen with pdo_mysql (and I am pretty sure it doesn't happen with PDO pgsql and sqlite either): you still get false without producing errors.
Here is a simplified version of the code:
// sqlsrv connection
$conn = new PDO("sqlsrv:Server=....;Database=....", "user", "password", array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ));
// mysql connection
// $conn = new PDO('mysql:host=....;dbname=....', 'user', 'password', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sql = "drop table if exists test;";
$res = $conn->query($sql);
$sql = "create table test (name varchar(10));";
$res = $conn->query($sql);
$sql = "insert into test (name) values ('Alice');";
$res = $conn->query($sql);
$sql = "select * from test";
$res = $conn->query($sql);
// fetch first record
$row = fetch_row_db($res);
var_dump($row);
// fetch again
$row = fetch_row_db($res);
var_dump($row);
// fetch again
$row = fetch_row_db($res);
var_dump($row);
function fetch_row_db(&$res)
{
try {
return $res->fetch();
}
catch(PDOException $e){
echo 'Error during record fetching.';
exit();
}
}
OUTPUT:
MySQL
array(2) { ["name"]=> string(5) "Alice" [0]=> string(5) "Alice" } bool(false) bool(false)
sqlsrv
array(2) { ["name"]=> string(5) "Alice" [0]=> string(5) "Alice" } bool(false) Error during record fetching.