Charles Krook
Charles Krook

Reputation: 3

My function can't output from database (PDO)

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

Answers (3)

Vlad Preda
Vlad Preda

Reputation: 9910

There are a few things that you need to read about:

  • error reporting. In order to make sure that you see all errors, I usually write this at the top of my scripts while debugging (just don't let these reach the production site):

error_reporting(E_ALL);
ini_set('display_errors', 1);
  • environments. In a function, you won't have access to variables outside that function, unless you specifically request this by using the global keyword.

$test = "A";
function testGlobal() {
    var_dump(isset($test)); // false

    global $test;
    var_dump(isset($test)); // true
}

testGlobal();

Upvotes: 0

Vivek S
Vivek S

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

Álvaro González
Álvaro González

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

Related Questions