lewashby Posted November 4, 2015 Share Posted November 4, 2015 (edited) [Linux] PHP Notice: Undefined variable: connection in /var/www/html/popreport/functions.php on line 23 PHP Fatal error: Call to a member function query() on a non-object in /var/www/html/popreport/functions.php on line 23 The fuction output in the following program is called from another file called records records-board.php If you look at the program below you'll see that I did define $connection above line 23 in the file functions.php And for the second error I'm really not getting it because that same foreach loop was working fine with the exact same argument list when it was in the file records-board.php, but now that I've copied most of the code from records-board.php and placed it in functions.php all the sudden my program can't see the variable $connection and has a problem with my foreach loop on line 23. Again, both of those lines worked fine when they were in another file. functions.php <?php //session_start(); // open a DB connectiong $dbn = 'mysql:dbname=popcount;host=127.0.0.1'; $user = 'user'; $password = 'password'; try { $connection = new PDO($dbn, $user, $password); } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } $sql = "SELECT full_name, tdoc_number, race, facility FROM inmate_board WHERE type = 'COURT'"; function output() { foreach($connection->query($sql) as $row) { echo "<tr><td>$row[full_name]</td></tr>"; } } ?> records-board.php <? include 'functions.php'; php output(); ?> Any ideas? Edited November 4, 2015 by lewashby Quote Link to comment Share on other sites More sharing options...
requinix Posted November 4, 2015 Share Posted November 4, 2015 Variables defined outside of functions are not available inside of functions. Pass what you need as arguments, like function output($connection, $sql) { Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted November 4, 2015 Share Posted November 4, 2015 Your code is not working because of variable scope. Variables define outside of functions are not available from within a function, same applies to variable defined inside a function are not available outside them. What you should be doing is defining your query within the function and then passing $connection as an argument when you call it. Quote Link to comment 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.