Storing chunks of code away from main code for use later

What is the correct procedure to store php code away from the main code so It can be used later in the script when needed?

So my intention was something like this -

In a separate file called common.php do something like this (this is not working code)

function bindStatements(){
 $stmt->bindColumn('name','$name');
 $stmt->bindColumn('address','$address');
 $stmt->bindColumn('country','$country');

}

Then, include the file in every page you need it, and echo the chuck where its needed. Like this:

$stmt = $dbh->prepare('SELECT name, address, country FROM users');

  $row = $stmt->execute();

  bindStatements();

  while ($row = $stmt->fetch() {
     print $name ."  ". $address ."  ". country."<br/>";
  }

Get my idea :slight_smile:

The only problem is, the code executes before and throws all errors. Is it somehow possible to do this?

That should work - in my quest to learn PHP I’ve just moved my database connection code to a separate file and used require_once() to include it, then added a function definition in that same file, without trouble.

What I did find, that I wasn’t expecting, is that even if you put the include/require code inside a pair of <?php and ?> tags, you must still have those tags within your included file, otherwise the contents just get displayed. Could that be the problem you’re having? If not, post the full included fle, and the errors that you’re receiving as ‘throws all errors’ kind of makes it hard to diagnose.

Hi Nordy,


function bindStatements() {
    $stmt->bindColumn('name','$name');
    $stmt->bindColumn('address','$address');
    $stmt->bindColumn('country','$country');
}

There are several problems with this approach. First, you don’t have access to variables outside of the function, you have to pass in the data you want to use as parameters. But, even if we passed in $stmt as an argument, bindColumn wouldn’t work here as you’re calling it within the scope of the function and the variables you bind won’t be available to the code outside. You’d get ‘undefined variable name’ errors from your print statement.