-1
Hello. I am trying to make a CRUD using PHP OO.
But when I run, I have an error in the preparation of the PDO class.
I have only the bank registration code and the bank connection code for now:
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 Orientation with PHP, so this way of receiving form data with object orientation may not be the best way to do it, but a beginner in studies like me, that’s what I was able to develop. And as I said, the code when executed is error in prepare...
Fatal error: Call to a Member Function prepare() on null
Could someone help me with this problem?
And I accept suggestions on how to better receive data from an object-oriented form.
Grateful!
I think the problem may be in html..
– Asura Khan
Here is my HTML http://pastebin.com/5G1x2AWL
– Gabriel
I looked over and couldn’t find any mistake in it
– Gabriel
Constructor does not return value.
– rray