[英]assigning a value to a passed parameter in a function
sqlsrv_prepare
requires query parameters to be passed by reference. sqlsrv_prepare
要求查询参数通过引用传递。 How do I pass values to a function and assign a value to it? 如何将值传递给函数并为其分配值? Below example, if I pass a value to the function and try to set the referenced value nothing is returned. 在下面的示例中,如果我将一个值传递给该函数并尝试设置引用的值,则不会返回任何内容。 If I assign the referenced variable a value outside of the function it returns data using those values even though I assign them something else in the function. 如果我在函数之外为引用变量分配了一个值,即使我在函数中分配了其他值,它也会使用这些值返回数据。
$getNotesSQL = "SELECT pat_id as PAT_ID, note_id as NOTE_ID, CONVERT(char(10), UPDATE_DATE, 120) as UPDATE_DATE ";
$getNotesSQL .= "FROM CLARITY.dbo.HNO_INFO";
$getNotesSQL .= " WHERE ip_note_type_c = ? ";
$getNotesSQL .= " AND (UPDATE_DATE >= ? AND UPDATE_DATE <= ?)";
if (!$getNotes = sqlsrv_prepare($clarity, $getNotesSQL, array(&$noteType, &$startDate, &$endDate))) {
echo "getNotesSQL couldn't be prepared\n";
die(print_r(sqlsrv_errors(), true));
}
$note_type = strval(1);
$start_date = "2017-05-29";
$end_date = "2017-07-11";
/**
$noteType = strval(1);
$startDate = "2017-07-01";
$endDate = "2017-07-11";
*/
function getNotes($getNotes, $note_type, $start_date, $end_date) {
$noteType = $note_type;
$startDate = $start_date;
$endDate = $end_date;
if (!sqlsrv_execute($getNotes)) {`enter code here`
echo "getNotes Couldn't be executed\n";
die(print_r(sqlsrv_errors(), true));
}
$noteArray = array();
$iii=0;
while ($row = sqlsrv_fetch_array($getNotes, SQLSRV_FETCH_ASSOC)) {
// print_r($row);
$noteArray[$iii] = $row;
$iii++;
}
echo "In getNote Function iii: (" . $iii .")\n";
print_r($noteArray);
return $noteArray;
}
$fetchedNotes = getNotes($getNotes, $note_type, $start_date, $end_date);
print_r($fetchedNotes);
I'm not entirely sure on the reasoning behind it - I think it might have something to do with scope - but you need to pass-by-reference the query parameter variables into the function too. 我不确定其背后的原因-我认为它可能与范围有关-但您也需要将查询参数变量传递给函数。
So something like this: 所以像这样:
function getNotes($getNotes, $note_type, $start_date, $end_date, &$noteType, &$startDate, &$endDate){
//perform query
}
Now that's a little ugly and quite annoying to maintain should the number of query parameters change. 现在,如果查询参数的数量发生变化,则很难维护。 However you could group the values and query parameters into arrays and pass the arrays into the function. 但是,您可以将值和查询参数分组到数组中,然后将数组传递到函数中。 Like this: 像这样:
function getNotes($getNotes, $values, $params){
foreach($params as $key => &$param){
$param = $values[$key];
}
// sqlsrv_execute
}
$values = [$note_type, $start_date, $end_date];
$params = [&$noteType, &$startDate, &$endDate];
$fetchedNotes = getNotes($getNotes, $values, $params);
I tried something similar to this on my users table, to test it, and it seems to work okay. 我在用户表上尝试了类似的方法进行测试,似乎还可以。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.