Jump to content

2 error messages on simple program


lewashby

Recommended Posts

[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 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.

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.