I can’t instantiate my class to db

Asked

Viewed 35 times

1

I made a class that connects in the bank and makes select, it happens that when I instate it in my index, does not work, from this error:

Notice: Undefined variable: Sql in C: xampp htdocs apitest index.php on line 8

Fatal error: Uncaught Error: Class name must be a Valid Object or a string in C: xampp htdocs apitest index.php:8 Stack trace: #0 {main} thrown in C: xampp htdocs apitest index.php on line 8

Sql.php class:

<?php 

class Sql extends PDO{
    private $conn;
    public function __construct(){
        $this->conn = new PDO("mysql:host=localhost;dbname=***","***", "***");
    }
    private function setParams($statment,$parameters = array()){
        foreach ($parameters as $key => $value) {
            $this->setParams($key,$value);
        }
    }
    private function setParam($statment,$key,$value){
        $statment->bindParam($key,$value);
    }

    public function query($rawQuery,$params = array()){
        $stmt = $this->conn->prepare($rawQuery);
        $this->setParam($stmt,$params);
        $stmt->execute();
        return $stmt;
    }
    public function select($rawQuery,$params = array()){
        $stmt = $this->query($rawQuery,$params);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}
 ?>

Index.php

<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require 'vendor/autoload.php';
require 'Sql.php';
$app = new \Slim\App;
$sql = new $Sql();    

//pagina inicial
$app->get('/',function(){
    echo 'Pagina Inicial';
});

//get de test
$app->get('/hello/{name}', function (Request $request, Response $response) {
    $name = $request->getAttribute('name');
    //$response->getBody()->write("Hello, $name");
    $usuarios = $sql->select("SELECT * FROM usuarios");
    echo json_encode($usuarios, 1);

    //return $response;
});
$app->run();

?>

1 answer

0

I managed to find out, I did the wrong instance:

$sql = new $Sql();    

There’s no $ in Sql, getting like this:

$sql = new Sql();    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.