Ruben Amendoeira
Ruben Amendoeira

Reputation: 9

PHP PDO - Using Constant variable undefined when instantiating PDO object

I am using PDO on Windows 7 using XAMPP 3.2.1 and I am having issues making it work, even though it works on my shared hosting server.

settings.php

<?php
define('DB_NAME', 'testdb'); //DB Name
define('DB_HOST', 'localhost'); //DB host
define('DB_USER','root'); //DB user
define('DB_PASSWORD', ''); //DB users password
?>

db.php

<?php

require_once("settings.php");

$db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',      DB_USER, DB_PASSWORD);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

?>

output.php

<?php

require_once("db.php");

function outPutPosts(){
    return $db->query("select * from replies limit 35"); <-- this line
}

?>

The error it presents:

Notice: Undefined variable: db in C:\xampp\htdocs\schoolplatform\output.php on line 10

Fatal error: Call to a member function query() on null in C:\xampp\htdocs\schoolplatform\output.php on line 10

Any help would be greatly appreciated :)

Upvotes: 0

Views: 228

Answers (3)

Rehmat
Rehmat

Reputation: 5071

You need to define the variable $db in your later function like this:

 <?php

    require_once("db.php");

    function outPutPosts(){
        $db = getConnection(); // define the variable $db here

        return $db->query("select * from replies limit 35"); 
    }

?>

Upvotes: 0

Aref Anafgeh
Aref Anafgeh

Reputation: 512

this issue is because the $db cant be acccessed directly inside function.you can use global keyword to access it inside your function like this:

function outPutPosts(){
 $db= $_GLOBAL['db'];
 return $db->query("select * from replies limit 35"); 
}

Upvotes: 1

Anto S
Anto S

Reputation: 2449

Inside db.php

<?php

require_once("settings.php");

function getConnection() {
       global $db;
       $db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset=utf8',      DB_USER, DB_PASSWORD);
       $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
       return $db;
}
?>

Then output.php

<?php

require_once("db.php");

function outPutPosts(){
    getConnection();

    return $db->query("select * from replies limit 35"); 
}

?>

Upvotes: 0

Related Questions