Jump to content

Empty object error unless MySQL connection is within function


atticus

Recommended Posts

I get an undeclared object error if I simply include the config.php file in either the parent page or the functions.php page.

 

This is the config.php script:

 

$mysqli = new mysqli("***");


/* check connection */
if ($mysqli->connect_errno) {
   printf("Connect failed: %s\n", $mysqli->connect_error);
   exit();
}

 

This is the functions page:

 

include 'config.php';

function calls($duplicates) {

if ($duplicates == 0) {

if ($result = $mysqli->query("SELECT * FROM calls WHERE duration >= 30")) {
   printf("Select returned %d rows.\n", $result->num_rows); } else {printf ("Errormessage: %s\n", $mysqli->error); } 

$result->close();

} else {

} 


}

 

So, I have to move the config.php file into the function in order to execute the query. I know this is a noob question, but I am just learning object oriented. Thanks in advance.

Link to comment
Share on other sites

I suggest you read up on functions and scope. It has nothing to do with OOP, you're trying to use a variable within a function without passing it to the function. 

 

If you want to actually make it OOP, it would probably be better in the long run and help with your scope issue, but it's hard to grasp for newbies so you might choose to just stick with functions and procedural for now. *shrug*

Link to comment
Share on other sites

The scope issue is that variables declared outside of functions (one scope) are not automatically available inside of functions (completely different scope).

 

I agree that you should try to make everything OOP (because right now only $mysqli is), but if you want to stick with procedural code just pass $mysqli to the function:

function calls($duplicates, $mysqli) {

(since you're using the same name for this variable you won't have to change your code to use it)

include 'config.php';
calls(123, $mysqli);

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.