[英]assigning a value to a passed parameter in a function
sqlsrv_prepare
要求查詢參數通過引用傳遞。 如何將值傳遞給函數並為其分配值? 在下面的示例中,如果我將一個值傳遞給該函數並嘗試設置引用的值,則不會返回任何內容。 如果我在函數之外為引用變量分配了一個值,即使我在函數中分配了其他值,它也會使用這些值返回數據。
$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);
我不確定其背后的原因-我認為它可能與范圍有關-但您也需要將查詢參數變量傳遞給函數。
所以像這樣:
function getNotes($getNotes, $note_type, $start_date, $end_date, &$noteType, &$startDate, &$endDate){
//perform query
}
現在,如果查詢參數的數量發生變化,則很難維護。 但是,您可以將值和查詢參數分組到數組中,然后將數組傳遞到函數中。 像這樣:
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);
我在用戶表上嘗試了類似的方法進行測試,似乎還可以。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.