Jump to content

2 error messages on simple program


Recommended Posts



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.


// open a DB connectiong
$dbn = 'mysql:dbname=popcount;host=';
$user = 'user';
$password = 'password';

    $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>";



include 'functions.php';
php output();

Any ideas?

Edited by lewashby
Link to comment
Share on other sites

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.

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.

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.