0

I cannot connect to the database within a PHP function, but have no difficulty outside the function. Googling around has not found solution. I am using PHP SQLSRV not MSSQL for the connection. This connection works elsewhere. This is the simple PHP:-

<?php
include("dbconfig.php"); 
//last line of this: $conn = sqlsrv_connect($serverName, $connectionInfo)

function listCalendar(){   
  $sql = "select Id from Calendar";
  $handle = sqlsrv_query($conn,$sql);
  while ($row = sqlsrv_fetch_object($handle)) {
  $ret= "result = ".$row->Id;
}
return $ret;
}

listCalendar(); ?> 

This does not even generate an empty "result = ". If the line function listCalendar(){ and closing tag } are commented out, and return $ret replaced by echo $ret, then the correct "result = 5" is echoed. Grateful for ideas as have wasted much time on this!

u_mulder
  • 54,101
  • 5
  • 48
  • 64
Paul
  • 117
  • 2
  • 9
  • *"but have no difficulty outside the function"* - It's a variable scope issue then. – Funk Forty Niner Jul 26 '16 at 19:22
  • 1
    You can use `global $conn` if this really is the way you want to solve it. – Perry Jul 26 '16 at 19:22
  • 1. You're returning from the function, so you need to echo it when you call it (`echo listCalendar();`). 2. You need to learn about *variable scope*. – Qirel Jul 26 '16 at 19:23
  • Aside from the scope issue, once that is resolve your `$ret` is only going to be the last value. If that is the intended do `top 1` and `order by id desc` (or whatever the mssql syntax is). This way you don't need to go through every record. – chris85 Jul 26 '16 at 19:24
  • Thanks! Now checking out about variable/global as completely unknown to me (a PHP newbie). Looking at the original question for which mine apparently a duplicate, there is NO way I would have even thought it relevant! – Paul Jul 26 '16 at 19:30
  • Thanks guys for spotting the issue so quickly! Now works, either by including the connection file within the function, or by converting $conn to a global. – Paul Jul 26 '16 at 19:42
  • @Paul keep in mind `$ret= "result = ".$row->Id;` is still overwriting on every iteration of the `while`. – chris85 Jul 26 '16 at 20:32

0 Answers0