-6

Probably a simple one so please excuse me.

At the top of my page I include a file:

<?
    require("common.php");
    ?>

Later on in my code I do the following:

  $stmt = $db->prepare($query);
  $result = $stmt->execute();
  $result = $stmt->fetchAll();

(the db connection files being in my include file).

This works fine, until I try and make the code a function For example: If I do

    function doAQuery(){
 $stmt = $db->prepare($query);
                    $result = $stmt->execute();
                    $result = $stmt->fetchAll();
}

It can't find the db details. Please can someone explain why?

Programatt
  • 776
  • 4
  • 10
  • 21
  • There is no `$query` available in your function. (And PHP would have told you that, if you only had set your error reporting to a sensible value – so please go do that _now_!) [Basics, Baby!](http://www.php.net/manual/en/language.variables.scope.php) – CBroe Nov 13 '13 at 11:22
  • Because `$db` is not in the scope of your function. Use `global` or make a DB class that does this for you while keeping `$db` as a local class variable. – h2ooooooo Nov 13 '13 at 11:23

3 Answers3

2

It's not a syntax issue. Your $db and $query variables are not available to your function scope. You can make them available by declaring global $db, $query as the first line of your function.

Tim
  • 6,904
  • 1
  • 31
  • 48
2

It's because $db is a global variable. PHP ignores it in the function scope unless you explicity declare it should be used.

function doAQuery() {
    global $db;
    $stmt = $db->prepare($query);
    $result = $stmt->execute();
    $result = $stmt->fetchAll();
}

Take a look at how variables scope works in PHP.

Guilherme Sehn
  • 6,178
  • 15
  • 35
0

Pass Query string to function,

function doAQuery($query){
Krish R
  • 21,556
  • 6
  • 47
  • 57