pdo_sqlsrv: how to recognize if fetch “false” is an error or empty recordset?

寵の児 提交于 2020-01-06 07:10:19

问题


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.

来源:https://stackoverflow.com/questions/53063059/pdo-sqlsrv-how-to-recognize-if-fetch-false-is-an-error-or-empty-recordset

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!