PDO connection to bank

Asked

Viewed 1,269 times

1

Good guys, I’m starting to study about PDO, but soon in my first activity is occurring an error, follows below all the information.

CODE Object.php

<?php

$cli = new Produtos();
$cli->insert();

CODE Product.php

<?php

class Produtos extends Conexao{

    public function insert(){

        $this->conectar();

    }
}

CODE Connected.php

class Conexao{

    private static $conexao;

        public function conectar(){
            try{

                if (!isset(self::$conexao)) {
                    self::$Conexao = new pdo("mysql:host=localhost; dbname = renanmeh_bd_projeto","root","")
                }

            }catch(PDOException $e){
                echo "Erro ao conectar ao banco ".$e->getMessage;
            }
            return self::$conexao
        }
    }

Basically, this is just a test, where I have object that instantiates the product class, and this product class makes a request in the connection class.

  • Which error? where is the message?

  • You entered your password on PDO, or just omitted in your question?

  • My BD has no password, it comes with root

1 answer

5


Your code has a number of minor errors:

On the line where the PDO is instantiated is missing a semicolon and variables, properties etc are case sensitive or either upper case and minuscules make difference the name of the property defined in the beginning is $conexao and not $Conexao(as seen in the assignment).

No echo inside catch getMessage() is a method so the use of parentheses is mandatory.

In Return also spoke a semicolon.

class Conexao{
   private static $conexao;
   public function conectar(){
        try{
            if (!isset(self::$conexao)) {
                //Não é $Conexao
                self::$conexao = new pdo("mysql:host=localhost; dbname=renanmeh_bd_projeto","root",""); //;
            }

        }catch(PDOException $e){
            echo "Erro ao conectar ao banco ".$e->getMessage(); //método
        }
        return self::$conexao; //;
    }
}

Recommended reading:

functions and methods in PHP are case-insensitive?

  • Error still appears. Fatal error: Class 'Products' not found in C: xampp htdocs pi PHPOO with PDO classes Object.php on line 3

  • In the archive objeto.php you need to do the class include. @Renan Rodrigues

  • That, I get here, thank you very much.

  • @Renan Rodrigues if I had interest can search for autoloading and psr-4, is a way to load the classes instead of using include.

Browser other questions tagged

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