1

I am using in my PHP file a function which is defines inside the PHP file. He structure of the code is like below

//--- db connection

$dbconn = pg_connect(...

// function definition

function myfunction(){
  $f_stmt = '.....'
  $f_result = pg_query_params($dbconn,$f_stmt, ....
  $val = pg_fetch_result($f_result, 'COL_VAL');
  return $val;
}

//---- general logic

  $stmt = '....'
  $result = pg_query_params($dbconn,$stmt, ....

   while ($row = pg_fetch_assoc($result)) {
      echo myfunction()
   }

When I am trying to use the same connection in the function $dbconn like tje sample above I am receiving a connection error. When I create a new connection $dbconn2 inside the function for its own usage it works. If this is the solution isn't it bad for the performance? or is there a proper way?

2
  • 1
    You need to make the $dbconn accessible inside the function global $dbconn; at the top of the function (before other code) will do the trick Commented Jan 7, 2014 at 13:59
  • Otherwise you can put the var as a parameter of the function and pass the data each time you call the function. Commented Jan 7, 2014 at 14:00

1 Answer 1

1

make your connection variable $dbconn to global variable ,

function myfunction(){
  global $dbconn;
  $f_stmt = '.....'
  $f_result = pg_query_params($dbconn,$f_stmt, ....
  $val = pg_fetch_result($f_result, 'COL_VAL');
  return $val;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.