atticus Posted January 2, 2013 Share Posted January 2, 2013 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. Quote Link to comment https://forums.phpfreaks.com/topic/272623-empty-object-error-unless-mysql-connection-is-within-function/ Share on other sites More sharing options...
Jessica Posted January 2, 2013 Share Posted January 2, 2013 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* Quote Link to comment https://forums.phpfreaks.com/topic/272623-empty-object-error-unless-mysql-connection-is-within-function/#findComment-1402855 Share on other sites More sharing options...
requinix Posted January 2, 2013 Share Posted January 2, 2013 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); Quote Link to comment https://forums.phpfreaks.com/topic/272623-empty-object-error-unless-mysql-connection-is-within-function/#findComment-1402857 Share on other sites More sharing options...
atticus Posted January 2, 2013 Author Share Posted January 2, 2013 Thanks y'all, very helpful. Quote Link to comment https://forums.phpfreaks.com/topic/272623-empty-object-error-unless-mysql-connection-is-within-function/#findComment-1402869 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.