我第一次使用sqlsrv_prepare()
/ sqlsrv_execute()
。到现在为止,我一直在使用sqlsrv_query()
。到目前为止,我能够获得我需要的数据,并且能够有效地使用数据。问题是我在结果数组中有两次值。
sqlsrv_prepare()
/ sqlsrv_execute()
的工作方式。
以下是我的PHP示例:
<?php
header("Content-type: text/javascript");
include($_SERVER['DOCUMENT_ROOT'] . "inc/dbconn.php");
include($_SERVER['DOCUMENT_ROOT'] . "inc/formaterrors.php");
// array populated from checkbox values
$items = (isset($_GET['checked'])) ? $_GET['checked'] : array();
// holds value of $i in foreach below - $i can't be used in sqlsrv_prepare() since it doesn't exist in this scope
$placeholder = '';
// variable from included dbconn.php file
$connectionOptions['Database'] = 'example_db';
$conn = sqlsrv_connect($serverName, $connectionOptions)
or die("Couldn't establish a database connection<br/>" . FormatErrors(sqlsrv_errors()));
$query = "
SELECT
detail.BILLNO,
detail.BILLTYPE,
detail.COMPONENTITEMCODE,
detail.QUANTITYPERBILL,
detail.REVISION,
header.BILLDESC1
FROM (BM_BILLDETAIL detail
JOIN BM_BILLHEADER header
ON (detail.BILLNO = header.BILLNO)
AND (detail.BILLNO = ?)
AND (header.REVISION = header.CURRENTBILLREVISION)
AND (detail.REVISION = header.CURRENTBILLREVISION)
and (detail.ENGINEERINGCHANGEDELNO = ''))
";
$results = array();
$stmt = sqlsrv_prepare($conn, $query, array(&$placeholder));
if(!$stmt)
{
die(print_r(sqlsrv_errors(), true));
}
foreach($items as $i)
{
$placeholder = $i;
if(sqlsrv_execute($stmt))
{
while($row = sqlsrv_fetch_array($stmt))
{
$results[] = $row;
}
} else
{
die(print_r(sqlsrv_errors(), true));
}
}
// diplay results as JSON
echo(var_dump(json_encode($results, JSON_PRETTY_PRINT)));
?>
以下是我在JSON中的结果示例:
{
"0": "TRC4009-C005",
"BILLNO": "TRC4009-C005",
"1": "",
"BILLTYPE": "",
"2": "110500001153-00",
"COMPONENTITEMCODE": "110500001153-00",
"3": "1.000000",
"QUANTITYPERBILL": "1.000000",
"4": "001",
"REVISION": "001",
"5": "TRC4009, 8155, Red 800W",
"BILLDESC1": "TRC4009, 8155, Red 800W"
}
所以我有key => value
对,这就是我想要的。我不想要“编号”键。只有字段名称键,即“BILLNO”,“REVISION”等
最终,我的工具仍然像这样工作;但是,我不希望每次发送/接收/处理的结果数量加倍。在大多数情况下,这将执行数百或数千次,结果的数量可能会有很大差异。
感谢任何帮助/见解。
答案 0 :(得分:2)
如果您只想获取文本键,则必须为sqlsrv_fetch_array
指定提取类型。默认提取类型为SQLSRV_FETCH_BOTH
,这就是您获取文本和数字键的原因。
您想改用sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)
。