Hello. I'm trying to make a CRUD using PHP OO.
But when I run I get error in prepare of the PDO class.
I have only for the moment the registration code in the bank and the connection code to the bank:
Banco.php
<?php
class Banco{
private $host = 'localhost', $usuario = 'root', $senha = '', $nomeBanco = 'rbtech', $conexao = null;
public function __construct(){
$this->conecta(); // Chama metodo para conexao
} // Fim construct
public function __destruct() {
if($this->conexao != null){
$this->conexao = null;
} // Fim destruct
}
public function conecta(){
try{
$this->conexao = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->nomeBanco, $this->usuario, $this->senha);
} catch (PDOException $e) {
die('Erro ao conectar com o banco' . $e->getMessage());
}
} // Fim conecta
}
Register.php
<?php
require_once '../Lib/Banco.php';
class Cadastro extends Banco{
// Porpriedades
public $nome, $sobrenome, $idade;
public function cadastrar(){
if($_POST){ // Verifica se é POST
$pdo = parent::__construct(); // Chama o construtor da classe Banco
$sql = "INSERT INTO clientes (nome, sobrenome, idade) VALUES(:nome, :sobrenome, :idade)"; // Query INSERT
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':nome', $nome);
$stmt->bindParam(':sobrenome', $sobrenome);
$stmt->bindParam(':idade', $idade);
if($stmt->execute()){
header('Location: ../index.php');
}else{
echo 'Erro ao cadastrar. ';
print_r($stmt->errorInfo());
}
}
} // Fim cadastrar
}
$cad = new Cadastro();
$cad->nome = $_POST['nome'];
$cad->sobrenome = $_POST['sobre'];
$cad->idade = $_POST['idade'];
$cad->cadastrar();
var_dump($cad);
I'm starting my studies in Object Oriented with PHP, so this way of receiving object-oriented form data might not be the best way to do it, but a beginner in studies like me was what I was able to develop. And as I said, the code when executed accuses error does not prepare ...
Fatal error: Call a member function prepare () on null
Can anyone help me with this problem?
And I welcome suggestions on how to better receive data from an object-oriented form.
Thank you!