Error when displaying contents of a mysql BD via a PHP API

Asked

Viewed 28 times

1

When creating an API for later consumption I get this error: Fatal error: Uncaught Error: Call to a Member Function prepare() on string in C: wamp64 www React test with API full src api Classcarros.php on line 9

I’m trying to show you all the data from a database created on phpmyadmin

Below follows my code:

File connection to the Database:

<?php

abstract class ClassConexao{

#conexão com o banco de dados
    public function conectaDB(){
        try{
            $Con=new PDO("mysql:host=localhost:8080;dbname=react","root","");
            return $Con;
        }catch (PDOException $Erro){
            return $Erro->getMessage();
        }
    }
}

?>

File manipulation and display of database records:

<?php

include("ClassConexao.php");

class ClassCarros extends ClassConexao{

    #Exibição dos carros em um json
    public function exibeCarros(){
        $BFetch=$this->conectaDB()->prepare("SELECT * FROM carros");
        $BFetch->execute();

        $J=[];
        $I=0;

        while($Fetch=$BFetch->fetch(PDO::FETCH_ASSOC)){
            $J[$I]=[
                "Id"=>$Fetch['Id'],
                "Marca"=>$Fetch['Marca'],
                "Modelo"=>$Fetch['Modelo'],
                "Ano"=>$Fetch['Ano']
            ];
            $I++;
        }

        header("Access-Control-Allow-Origin:*");
        header("Content-type: application/json");
        echo json_encode($J);
    }
}

?>

my index.php:

<?php

include("ClassCarros.php");
$Carros=new ClassCarros();
$Carros->exibeCarros();

?>

I’ve tried everything, put "__" in the constructor ("exibeCarros()") put a Return, but nothing works.

1 answer

0

According to your error report, your function connectedB() is a string. It checks if it is returning a connection. Because the report says that prepare it is being called in a string.

  • I checked and as the posted codes, I can’t find the solution to the error. As far as I can see, the function connedB() is not a string.

  • What is the result returned in $Bfetch? I believe it is something with your connection. A suggestion variable names always start with minuscule letters, upper case letters are reserved for classes such as Classcarro. You can find more about this here https://php-fig.org/psr/psr-12/

Browser other questions tagged

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