Skip to content
Advertisement

Fatal error: Uncaught Error: Call to a member function query() on null in C:xampphtdocsshopindex.php

I have a problem with my code I’m getting this error message

Fatal error: Uncaught Error: Call to a member function query() on null in C:xampphtdocsshopindex.php:11 Stack trace: #0 {main} thrown in C:xampphtdocsshopindex.php on line 11

index.php

<?php

require_once __DIR__.'/function/database.php';

$sql = 'SELECT id, title, description, price FROM products';

$result = getDB()->query($sql);
require __DIR__.'/templates/main.php';

./function/database.php

<?php 
function getDB() { 
    static $db;

    if ($db instanceof PDO){ 
        return $db; 
    }

    require_once CONFIG_DIR.'/database.php'; 

    $dsn = sprintf("myqsl:host=%s;dbname=%s;charset=%s",DB_HOST,DB_DATABASE,DB_CHARSET); 

    return $db; 
}

Advertisement

Answer

You forgot to create PDO connection:

<?php 
function getDB(){ 
    static $db; 
    if($db instanceof PDO){ 
        return $db; 
    } 
    require_once CONFIG_DIR.'/database.php'; 
    $dsn = sprintf("myqsl:host=%s;dbname=%s;charset=%s",DB_HOST,DB_DATABASE,DB_CHARSET); 
    $db = new PDO($dsn); // ← HERE
    return $db; 
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement