繁体   English   中英

向函数中的传递参数分配值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM