simple select返回意外结果

时间:2013-06-29 17:53:58

标签: php sql-server linux pdo odbc

运行此代码会返回意外结果

<?php
error_reporting(-1);
try{
    $pdo = new PDO('odbc:Driver={SQL Server Native Client 11.0};Server=192.168.178.11;Database=test;','sa', 'secret');
    $s = $pdo->prepare('SELECT * FROM test');
    if($s->execute()){
        var_dump($s->fetchAll());
    }
    $s = $pdo->prepare('SELECT * FROM test WHERE id = ?');
    if($s->execute(array(1))){
        var_dump($s->fetchAll());
    }
}catch(Exception $e){
    echo $e->xdebug_message;
}

返回

array (
    0 => 
    array (
      'id' => '1',
      0 => '1',
      'test' => 'test      ',
      1 => 'test      ',
    ),
    1 => 
    array (
      'id' => '2',
      0 => '2',
      'test' => 'test2     ',
      1 => 'test2     ',
    ),
    2 => 
    array (
      'id' => '3',
      0 => '3',
      'test' => 't3        ',
      1 => 't3        ',
    ),
)

你可以看到第二个语句失败

(注意我正在运行gentoo linux 64,我在win7 64虚拟机上连接到SQL Server 2012)

1 个答案:

答案 0 :(得分:1)

我使用MySQL获得第二个语句。您可能需要使用SQL Server使用closecursor释放与语句之间的连接。

$pdo = new PDO('odbc:Driver={SQL Server Native Client 11.0};Server=192.168.178.11;Database=test;','sa', 'secret');
    $s = $pdo->prepare('SELECT * FROM test');
    if($s->execute()){
        var_dump($s->fetch());
    }
    $s->closeCursor();// ADD THIS for SQL Server
    $s = $pdo->prepare('SELECT * FROM test WHERE id = ?');
    if($s->execute(array(1))){
        var_dump($s->fetch());

PS fetch()仅获取1行。您应该只在var_dump()

中有1个ID