I don't understand PDO's behavior about stored procedure and I need some explanations (and maybe a solution to my problem).
I'm using SQL Server 2008 R2 with PHP 5.4 and Apache 2.2. I'm calling a stored procedure with 2 parameters using PDO (with SQLSRV drivers):
$pdoStmt = $pdo->prepare('MY_STORED_PROCEDURE ?, ?');
$pdoStmt->bindValue(1, 'MyValue1', PDO::PARAM_STR);
$pdoStmt->bindValue(2, 'MyValue2', PDO::PARAM_STR);
$pdoStmt->execute();
Okay, here, everything works perfectly. The result of the stored procedure called is an array so I should use fetchArray(). So I do that:
$result = $pdoStmt->fetchArray();
BUT the result is empty. And I don't know why, I have to call several time nextRowSet() to get the result. So I do that:
do {
$result = $pdoStmt->fetchAll(PDO::FETCH_ASSOC);
} while ($pdoStmt->nextRowSet());
Then I have my result ! Yay....
The stored procedure works when I execute it directly in the SQL Server (I have a correct result with the same parameters).
So why I have to do that and is there any solution about that ? I don't want to call nextRowSet() for nothing...
Thanks in advance for your response.
After researches, here my own fetchArray()
method :
function fetchArray($single = false)
{
$this->row = array();
do {
$tmp = $this->cur->fetchAll(PDO::FETCH_ASSOC);
$cnt = $this->cur->columnCount();
if($cnt) {
$this->nb_fields = $cnt;
for($i=0; $i<$cnt; $i++){
$this->fields[] = $this->cur->getColumnMeta($i)['name'];
}
}
$this->row = array_merge($this->row, $tmp);
} while ($this->cur->nextRowSet());
if (count($this->row) == 1 && $single == true) {
$this->row = $this->row[0];
}
if (empty($this->row)) {
$this->row = false;
}
return $this->row;
}
Hope that will help :-)
There is no fetchArray()
method in PDO, if you want to get an array, you can do something like:
$result = $pdoStmt->fetch(PDO::FETCH_ASSOC);
To get an associative array.