Call to a member function query () on null in /var/www/html/mvc/models/Announcements.php:9

0

Can you help me with this error?

  

Fatal error: Uncaught Error: Call to a member function query () on null   in /var/www/html/mvc/models/Announces.php:9 Stack trace: # 0   /var/www/html/mvc/controllers/homeController.php(10):   Ads- & getquantity () # 1 /var/www/html/mvc/core/Core.php(37):   homeController- > index () # 2 /var/www/html/mvc/index.php(20):   Core- > run () # 3 {main} thrown in /var/www/html/mvc/models/Announces.php   online 9

Ads.php

<?php
class Anuncios extends model
{
    public function getQuantidade()
    {
        $sql = "SELECT COUNT(*) as quantidade FROM epi";
        $sql = $this->db->query($sql);

        if ($sql->rowCount() > 0) {
            $sql = $sql->fetch();
            return $sql['quantidade'];
        } else {
            return 0;
        }
    }
}

config.php

<?php
require_once 'environment.php';
$config = array();

if (ENVIRONMENT == "development") {
    define("BASE_URL", "http://localhost/mvc/");
    $config['host'] = 'localhost';
    $config['dbname'] = 'self_epi';
    $config['dbuser'] = 'root';
    $config['dbpass'] = '32051217';
} else {
    //define("BASE_URL", "http://www.site.com.br");
    $config['host'] = 'localhost';
    $config['dbname'] = 'selfepi';
    $config['dbuser'] = 'root';
    $config['dbpass'] = 'Admin';
}
global $db;
try {
    $db = new PDO("mysql:dbname=".$config['dbname'].";host=".$config['host'], $config['dbuser'], $config['dbpass']);
    echo 'conectou';
} catch(PDOException $e) {
    echo "Erro: ".$e->getMessage();
}

model.php

<?php
class model
{
    protected $db;
    public funciton __construct()
    {
        global $db;
        $this->db = $db;
    }
}

controller

<?php

class homeController extends controller
{
    public function index()
    {
        $anuncios = new Anuncios();
        $usuarios = new Usuarios();
        $dados = array(
            'quantidade' => $anuncios->getQuantidade(),
            'nome' => $usuarios->getNome(),
            'idade' => $usuarios->getIdade()
        );
        $this->loadTemplate('home',$dados);
    }
}
    
asked by anonymous 21.06.2018 / 13:29

2 answers

1

put global $db; and see if it gets

    
21.06.2018 / 16:12
0

Hello Helder try to change the name of the variable that receives the query, it may be conflicting because you are declaring the same variable ($ sql) twice.

$res = $this->db->query($sql);
if ($res->rowCount() > 0) {
        $sql = $res->fetch();
        return $sql['quantidade'];
    } else {
        return 0;
    }
    
21.06.2018 / 18:08