-3

Did a var_dump - returned object(PDO)#1 (0) { }

Code for my database connection below:

<?php

$config['db'] = array

    (

        'host'      => 'localhost',
        'dbname'    => 'journal',
        'username'  => 'root',
        'password'  => ''


    );


        $dbc = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
        var_dump($dbc);

?>

When I try to use the $dbc variable it returns the errors below:

Notice: Undefined variable: dbc in C:\xampp\htdocs\journal\data\functions.php on line 21

Fatal error: Call to a member function prepare() on a non-object in C:\xampp\htdocs\journal\data\functions.php on line 21

Line 21:

$appendEntries = $dbc->prepare("SELECT * FROM `entries`");
hakre
  • 193,403
  • 52
  • 435
  • 836
John Smith
  • 75
  • 2
  • 7

1 Answers1

2

I'm imagining your code in functions.php looks something like this

require_once 'db.php';

function somethingSomethingEntries() {
    $appendEntries = $dbc->prepare("SELECT * FROMentries");
}

In the scope of somethingSomethingEntries, $dbc does not exist. You should pass it in as an argument, eg

function somethingSomethingEntries(PDO $dbc) {
    $appendEntries = $dbc->prepare("SELECT * FROMentries");
}

and call it with

require_once 'db.php';

somethingSomethingEntries($dbc);
Phil
  • 157,677
  • 23
  • 242
  • 245