0

I'm learning PHP, and can't seem to figure out if loops can be run inside a function.

My code works when not inside a function, but I cannot to get it to output when I wrap it in a function.

I'm trying to input an agency name ($jur) and get a list of names associated with that name from a data base.

function jur($conn, $jur){

    // SQL that runs the search in the data base for all employees associated with an agency

    $EmployeeListSQL = "SELECT emp.NAME as NAME, jur.NAME as AGENCY FROM SMARTCM . dbo . EMPMAST as emp
                      inner join SMARTCM . dbo . EMP_TO_JURIS as empjur
                      on emp.UniqueKey = empjur.FK_EMP_KEY
                      inner join SMARTCM . dbo . JURISDICT as jur
                      on empjur.FK_JURIS_KEY = jur.UniqueKey
                      where jur.name = '$jur'";

    $employeeListSET = sqlsrv_query($conn, $EmployeeListSQL);



    // create an array with all the names fetched from the data base

    while($employee = sqlsrv_fetch_array( $employeeListSET, SQLSRV_FETCH_ASSOC)){
        $employeeListArray[] = $employee['NAME'];
    }


    // list all the array items

    foreach($employeeListArray as $employee){
        echo   $employee . "<BR>";
    }
}


// Try to call the function list
jur($conn, 'Girard');
zhwatts
  • 84
  • 1
  • 11
  • 4
    `$conn` isn't in scope inside the function - [PHP Docs on variable scope](http://php.net/manual/en/language.variables.scope.php) – Mark Baker Aug 11 '16 at 23:29
  • Ok that makes sense! so because I'm calling my connection "outside" the function, it's preventing my SQL from running? – zhwatts Aug 11 '16 at 23:32
  • 1
    Pass the $conn variable created outside the function as an argument to your function – Mark Baker Aug 11 '16 at 23:38
  • or declare it as a GLOBAL – Arthur Nicoll Aug 11 '16 at 23:40
  • 5
    @ArthurNicoll Or better still Dont Declare It As A Global, pass it as a parameter – RiggsFolly Aug 11 '16 at 23:48
  • I'm curious: What made you think the problem might be that loops don't work inside functions? The warning message should have been "Undefined variable $conn". – Barmar Aug 12 '16 at 00:39
  • for some reason error reporting was not turned on by default, but after I set display_errors i am getting an undefined variable error. – zhwatts Aug 12 '16 at 00:45
  • the error I'm getting still makes me thing theres a problem with my loop some how... the error states "Undefined variable: employeeListArray" – zhwatts Aug 12 '16 at 00:51
  • I should say, I updated my code to pass my connection string – zhwatts Aug 12 '16 at 00:53
  • You are getting that error because you are not defining your `employeeListArray` array in your function. You should put `employeeListArray = array();` at the beginning of your function. – Cave Johnson Aug 12 '16 at 01:17
  • I tried that, it clears my errors but for some reason the while loop still isn't working to set the array elements... – zhwatts Aug 12 '16 at 01:22

0 Answers0