带有SQL Server的PHP PDO和准备好的语句 [英] PHP PDO with SQL Server and prepared statements

查看:75
本文介绍了带有SQL Server的PHP PDO和准备好的语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经有许多与此类似的问题.但是,我还没有找到使此代码正常工作的方法.

There are a number of similar questions to this already posted. However I have not found a way to get this code working.

我正在从本机MSSQL查询更新PHP代码库以使用PDO,尤其是使用ODBC.这是我尝试过的旧代码和两个变体.

I am updating a PHP codebase from native MSSQL queries to use PDO, specifically to use ODBC. Here is the old code and two variations I have tried.

旧样式:有效,这会产生一系列预期结果.

Old style: Works, This produces an array of expected results.

$db = mssql_connect('connection', 'user', 'password');
mssql_select_db('database', $db);

$sp = mssql_init('procedure', $db);
$param=1;
$results=[];
mssql_bind($sp,'@param',$param,SQLINT4,FALSE,FALSE);
$spRes = mssql_execute($sp);

while ($row = mssql_fetch_array($spRes, MSSQL_ASSOC)) $results[] = $row; 
mssql_free_statement($sp);
var_dump(results);

将T-SQL与PDO结合使用几乎可以正常工作:只要不尝试绑定任何参数,我都会得到结果.

Using T-SQL with PDO almost works: I get results as long as I don't try to bind any parameters.

$pdo = new PDO($'dblib:host=connection', 'user', 'password');
$pdo->query('use database');

$sp= $db->prepare("EXEC procedure");
$sp->execute();

while ($row = $sp->fetch(PDO::FETCH_BOUND)) $results[] = $row; 
$sp->closeCursor();
var_dump(results);

产生许多期望结果的数组.但是,任何绑定参数的尝试都会导致$results为空数组.没有错误报告.

Produces an array of many expected results. However any attempt to bind parameters leads to $results being an empty array. No errors are reported.

$sp= $db->prepare("EXEC procedure :param");
$sp->bindParam(':param', $param, PDO::PARAM_INT);

这将导致结果集为空,并且不会报告任何错误.

This leads to an empty result set, and reports no errors.

使用ODBC"SQL" 似乎根本不起作用:

$pdo = new PDO($'dblib:host=connection', 'user', 'password');
$pdo->query('use database');

$sp= $db->prepare("CALL procedure");
$sp->execute();

while ($row = $sp->fetch(PDO::FETCH_BOUND)) $results[] = $row; 
$sp->closeCursor();
var_dump(results);

$results为空;有或没有参数,它似乎都不起作用.

$results is empty; with or without parameters, it doesn't seem to work.

系统详细信息:在带有unixodbc&的Ubuntu Trusty(14)上运行PHP 5.5.9.安装了freetds.

System details: Running PHP 5.5.9 on Ubuntu Trusty (14) with unixodbc & freetds installed.

我真的很感激PHP PDO的一个工作示例,该示例使用MSSQL调用存储过程和绑定参数.

I would really appreciate a working example of PHP PDO calling stored procedures and binding parameters with MSSQL.

推荐答案

尝试一下..

$result = array();

$sp= $db->prepare("EXECUTE dbo.procedure :param");
$sp->bindParam(":param", $param, PDO::PARAM_INT);
$sp->execute();

$result = $sp->fetchall(PDO::FETCH_OBJ);

这篇关于带有SQL Server的PHP PDO和准备好的语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆