简体   繁体   中英

assigning a value to a passed parameter in a function

sqlsrv_prepare requires query parameters to be passed by reference. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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