开发者

PHP / Mongo: query won't work if inside a function;

The following php throws up this error...

Fatal error: Call to a member function findOne() on a non-object in J:\xampplite\htdocs\Produkshunator\home.back.php on line 27

Here's the php...

<?php
/***********************************************
 * 
 * Make Connection
 * 
*************************************************************/  

    $conn = new Mongo();

    if($_POST['mod'] == "add") {

        add_data();
    }

/***********************************************
 * 
 * Add data
 * 
*************************************************************/

    function add_data() {

        $doc         = array("email" => $_POST['email']);
        $prod        = array("productions");

/*line 27 -->*/     $category_exists = $conn -> registration -> users -> findOne($doc, $prod);   // <--- line 27

            if (in_array($_POST['new_title'], $category_exists['productions'])){

                $response = array("errormsg" => "That production already exists, please use a unique title.");

            } else {

                $newdata = array('$push' => array("productions" => $_POST['new_title']));

                $doc = array("email" => $_POST['email']);

                $conn -> registration -> users -> update($doc, $newdata);

                $response = array("production" => $_POST['new_title']);
            }

        reply($response); 
    }

/***************************************************
 * 
 *  Reply
 *  
***************************************************************/
    function reply($response) {

        echo json_encode($response);
    }
?>

... however ... when I comment out the call to add_data() and its function declaration so its all part the 'if' statement it works without a hitch...

    if($_POST['mod'] == "add") {

//      add_data();
//  }

/***********************************************
 * 
 * Add data
 * 
****************开发者_开发技巧*********************************************/

//  function add_data() {

Is there a workaround, or just something I'm missing. Because otherwise this could get very messy, very fast.


You cannot access variables declared outside a function unless you declare global $variable. See the documentation on variable scope.

$foo = "foo";

# Doesn't print anything
function print_foo(){
   print $foo;
}

# Prints "foo"
function print_foo(){
   global $foo;
   print $foo;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜