Jump to content

Why can't I run $q = $conn->query($sql); in a function?


Q695

Recommended Posts

:suicide:  :confused:  :suicide:

for some reason I'm getting this error heavily:

"Fatal error: Call to a member function query() on a non-object in..."

 

All the function does is:
 

function grab_function($functionName, $language){
global $conn;
$sql = "SELECT * FROM  `functions`
        WHERE  `language` =  '$language'
        AND  `name` =  '$functionName'
        LIMIT 1";
        $q = $conn->query($sql);
        $q->setFetchMode(PDO::FETCH_ASSOC);
        $result = $q->fetch();
    $source = $result['source'];
    eval($source);
}

Where's the bug at?

  On 3/4/2015 at 9:37 PM, cyberRobot said:

It sounds like $conn isn't pointing to your database object. Did you open a database connection before calling grab_function()? Was the database object assigned to $conn.

I'm giving my function permission to go out, and grab the variable $conn, and take it home right?

 

specific line is:         $q = $conn->query($sql);

  On 3/4/2015 at 9:43 PM, Q695 said:

I'm giving my function permission to go out, and grab the variable $conn, and take it home right?

 

Your function does declare $conn as global. So it should grant the function access to the database object.

 

However, the error says that $conn isn't an object. That leads me to believe that the database connection wasn't made before calling the function. Or the database object wasn't assigned to $conn. Maybe it's being stored in $con, $dbs, or something else.

  On 3/4/2015 at 9:55 PM, Q695 said:

Should I switch to mysqli to try to solve it that way?

 

You would still be dealing with a database object, so it shouldn't make a difference.

 

 

  On 3/5/2015 at 1:26 AM, Q695 said:

Without wrapping it in a function it works, but when I do it breaks the function.

 

It may help if we see more code. Of course, you'll want to remove an sensitive information such as the database username and password.

 

 

Have you tried passing the database object as a function argument?

<?php
function grab_function($functionName, $language, $conn){
    $sql = "SELECT * FROM  `functions`
            WHERE  `language` =  '$language'
            AND  `name` =  '$functionName'
            LIMIT 1";
    //... 
}
?>

Also, do you have all PHP errors and warnings being displayed? To make sure, you can add the following to the top of your script during the debugging process:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.