tags:

views:

50

answers:

2

Hi everyone,

I am trying to make a function to pull a page's content from a MySQL table using a PDO Prepare statement. My code works just fine outside of the function I defined, but no matter what I do it will not work within the function - I receive the following error:

Fatal error: Call to a member function prepare() on a non-object in /home/tappess1/public_html/pages/stations.php on line 6

Here is my PHP:

function getPageContent($page) {
        $st = $db->prepare("SELECT * FROM content WHERE title LIKE ?");
        $st->execute(array($page));
        $pageContent = $st->fetch();
        $text = wordwrap($pageContent['content'], 100, "\n");
        $tabs = 4;
        $text = str_repeat(chr(9), $tabs) . str_replace(chr(10), chr(10) . str_repeat(chr(9), $tabs), $text);
        echo $text;
    }

and then

<?php getPageContent(Main);?>

I have even tried using a query instead of prepare statement, simply calling getPageContent() and I receive the same error.

Thanks!

+2  A: 

You are trying to access the variable $db which is outside your function's scope.

Either re-initialize your database within the function $db = new PDO...., or - probably better and easier in your case - import the global variable:

function getPageContent($page) {
  global $db;

Where and how to best store the global database object is subject of a lot of discussion. If you want to get into it, here is one place to start (there are many others on SO, too). But if you're just getting into PHP, I'd say using the global variable is fine.

Pekka
It's amazing how fast questions are answered here. A light bulb went off in my head right after I posted and I realized what was going on, solved it by including the connection script to the function. Your solution is much better, thanks a bunch!
NightMICU
@karim me too. -
Pekka
A: 

The variable $db is not known within your function.

dutch