PDO does not work inside function

I am trying to make a function to pull the contents of a page from a MySQL table using the PDO Prepare statement. My code works fine outside of the function that I defined, but no matter what I do, it will not work inside the function - I get the following error:

Fatal error: call prepare () member function for non-object in / home / tappess 1 / 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 even tried using the query instead of the prepare statement by simply calling getPageContent () and I get the same error.

Thanks!

+4
source share
2 answers

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

Either reinitialize your database in the function $db = new PDO.... , or, perhaps, it is better and easier in your case to import a global variable:

 function getPageContent($page) { global $db; 

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

+13
source

In your function, the variable $ db is unknown.

+1
source

Source: https://habr.com/ru/post/1310039/


All Articles