Using typed bound parameters with PHP PDO-ODBC, unixODBC and FreeTDS

馋奶兔 提交于 2019-12-01 17:16:46

I know that this is an old issue, but I wanted to post my solution for anyone having the same problem.

I was able to resolve this issue by changing my TDS Version from 7.1 to 7.2. I am not experiencing any issues anymore.

Hopefully this helps!

On the FreeTDS mailing list, I got the confirmation that SQLDescribeParam is not supported in FreeTDS. But when SQLDescribeParam is not supported, PDO_ODBC is to blame for using LONGVARCHAR (ie. text).

The same code worked on a Windows workstation with PDO ODBC (PHP Version 5.2.9, ODBC library Win32)

A workaround for this issue to treat every parameter as LONGVARCHAR and use explicit type conversion in queries. MS SQL Server only supports LONGVARCHAR => *CHAR conversions. To convert, I had to use thing like CAST(CAST(:number AS varchar) AS INTEGER) or CAST(CAST(:birthdate AS varchar) AS datetime). It is bad, ugly and probably a performance hog but it works.

In my case, I had a call to a stored procedure, which returns records... but with some inserts in it... I managed to get it working by adding:

SET NOCOUNT ON

In your insert case, this could be similar, as the MSSQL outputs the result of the insert but PDO does not understand it.

Doing the cast as you said did not work for me.

An example on how to reproduce the behavior:

create procedure sptest 
    @var int
as
begin 
    create table #tmp (var int)
    insert into #tmp values (@var)
    select * from #tmp
end

And the PHP code:

$query = "exec sptest @var=:var";
$dbh = new PDO (SQLSVR_DRIVER);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$rs = $dbh->prepare($query);
$rs->bindParam('var', 1, PDO::PARAM_INT);
$rs->execute();
while ($row = $rs->fetch(PDO::FETCH_ASSOC))
    var_dump($row);

The fix is:

create procedure sptest 
    @var int
as
begin 
    set nocount on
    create table #tmp (var int)
    insert into #tmp values (@var)
    select * from #tmp
end

That's it!

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