Reputation: 3
This function wont echo the $title, the code inside the function works great when I put it directly in the index file but when I make a function out of it it doesn't echo anything.
I can make a function just echoing "Hello"
but this wont work.
I have checked that the connection file is included.
function title(){
$query = $db->prepare("SELECT * FROM posts");
$query->execute();
$get = $query->fetch();
$title = $get['title'];
echo $title;
}
Upvotes: 0
Views: 56
Reputation: 9910
There are a few things that you need to read about:
error_reporting(E_ALL);
ini_set('display_errors', 1);
global
keyword.$test = "A";
function testGlobal() {
var_dump(isset($test)); // false
global $test;
var_dump(isset($test)); // true
}
testGlobal();
Upvotes: 0
Reputation: 2051
ou 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.
Upvotes: 0
Reputation: 146460
You are using an undefined variable ($db
). If you don't get error messages that means that you haven't configured PHP to display error messages. That's something you need to fix before you go further; it's impossible to code properly without the aid of error messages. Here's a brief explanation.
I'd suggest doing this instead:
function title(Database $db){
}
... where Database
is the class name $db
belongs to (maybe PDO
according to question tags).
But please don't just apply the fix and move on: make sure you get notified of the slightest notice.
Upvotes: 1