Problem entering data into BD with PDO

Asked

Viewed 457 times

0

My mistake:

Fatal error: Call to Undefined method DB::prepare() in C: xampp htdocs atTheClub Adm classes houses.php on line 36

Archives:

php houses.

class casas extends Crud{

protected $table = 'casas';
private $nomeCasa;
private $pessoaContatoCasa;
private $telefoneCasa;
private $emailCasa;
private $enderecoCasa;

public function setNomeCasa($nomeCasa){
    $this->nomeCasa= $nomeCasa;
}

public function setPessoaContatoCasa($pessoaContatoCasa){
    $this->pessoaContatoCasa = $pessoaContatoCasa;
}

public function setTelefoneCasa($telefoneCasa){
    $this->telefoneCasa= $telefoneCasa;
}

public function setEmailCasa($emailCasa){
    $this->emailCasa= $emailCasa;
}

public function setEnderecoCasa($enderecoCasa){
    $this->enderecoCasa= $enderecoCasa;
}   

public function insert(){

    $sql = "INSERT INTO $this->table (nomeCasa, pessoaContatoCasa, telefoneCasa, emailCasa, enderecoCasa) VALUES (:nomeCasa, :pessoaContatoCasa, :telefoneCasa, :emailCasa, :enderecoCasa)";
    $stmt = DB::prepare($sql);
    $stmt->bindParam(':nomeCasa', $this->nomeCasa);
    $stmt->bindParam(':pessoaContatoCasa', $this->pessoaContatoCasa);
    $stmt->bindParam(':telefoneCasa', $this->telefoneCasa);
    $stmt->bindParam(':emailCasa', $this->emailCasa);
    $stmt->bindParam(':enderecoCasa', $this->enderecoCasa);
    return $stmt->execute();
}

}

crud.php

require 'db.php'; abstract class Crud extends DB{ protected $table; abstract public function insert(); abstract public function update($idCasa); }

I deleted the delete and search functions to decrease the code snippet.

And below the file where is the DB class that PHP says is the error:
db.php
require 'config.php'; class DB extends PDO{ private static $instance; public static function getInstance(){ if(!isset(self::$instance)){ try { self::$instance = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASS); self::$instance->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); self::$instance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ); } catch (PDOException $e) { echo $e->getMessage(); } }; return self::$instance; }; public static function prepare($sql){ return self::getInstance()->prepare($sql); }; };

So, first I had not extended the PDO class to the BD class, I thought that would solve, tested and generated the same error, in case anyone knows what is happening, I really appreciate it! I deleted all the checks, left only what I was supposed to need to enter the data.

  • For now note that you are using Singleton, and another thing is, when you inherit from the class PDO no longer need to use the new PDO(...), you can just use parent::__construct($dsn, $user, $pass, $opcoes), and very easily you could use parent::prepare instead of what you have there. If there is time and still not solved the problem, I analyze your problem better.

2 answers

1


Your connection class is a little confused, I think there is no need to extend it to the PDO class because, PDO is a native php class, there is also no need for the Static prepare() function. try to make your class simpler perhaps;

class BD{   
    /**
     * [$pdo será objeto com a conexão]
     * @var [obj]
     */
    private static $pdo; 
    /**
     * [$host Host]
     * @var string
     */
    private static $host = 'seu_host';
    /**
     * [$name nome do banco]
     * @var string
     */
    private static $name = 'seu_banco';
    /**
     * [$charset charset utilizado no banco]
     * @var string
     */
    private static $charset = 'utf8';
    /**
     * [$user usuário do banco]
     * @var string
     */
    private static $user = 'usuario_do_banco';
    /**
     * [$passwd senha do banco]
     * @var string
     */
    private static $passwd = 'senha_do_usuario_do_banco';

    /**
     * [__construct Construtor da classe]
     */
    private function __construct(){}   

    /**
    * [getInstance Verifica se existe uma instância da conexão, caso nao exista retorna uma nova.]
    * @return [obj] [retorna objeto da conexão]
    */
    public static function getInstance() {   
        if (!isset(self::$pdo)):  
            try {   
                $opcoes = array();   
                self::$pdo = new \PDO("mysql:host=" .self::$host. "; dbname=" . self::$name . "; charset=" . self::$charset . ";", self::$user, self::$passwd, $opcoes);   
                self::$pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);  
            } catch (PDOException $e) {   
                print "Erro com a conexão: " . $e->getMessage();   
            }   
        endif;   
        return self::$pdo;   
    }       
}  

Already in your class php houses. you can create a private object called $Pdo to be instilled into the class constructor by making it available as the connection object for all its functions in the class.

require 'db.php';

protected $table = 'casas';
private $nomeCasa;
private $pessoaContatoCasa;
private $telefoneCasa;
private $emailCasa;
private $enderecoCasa;
private $pdo; // Será nossa conexão na classe

function __construct()
    {
        $this->pdo = BD::getInstance();// instancia conexão
    }

public function setNomeCasa($nomeCasa){
    $this->nomeCasa= $nomeCasa;
}

public function setPessoaContatoCasa($pessoaContatoCasa){
    $this->pessoaContatoCasa = $pessoaContatoCasa;
}

public function setTelefoneCasa($telefoneCasa){
    $this->telefoneCasa= $telefoneCasa;
}

public function setEmailCasa($emailCasa){
    $this->emailCasa= $emailCasa;
}

public function setEnderecoCasa($enderecoCasa){
    $this->enderecoCasa= $enderecoCasa;
}   

public function insert(){

    $sql = "INSERT INTO {$this->table} (nomeCasa, pessoaContatoCasa, telefoneCasa, emailCasa, enderecoCasa) VALUES (:nomeCasa, :pessoaContatoCasa, :telefoneCasa, :emailCasa, :enderecoCasa)";
    $stmt = $this->pdo->prepare($sql); 
    $stmt->bindParam(':nomeCasa', $this->nomeCasa);
    $stmt->bindParam(':pessoaContatoCasa', $this->pessoaContatoCasa);
    $stmt->bindParam(':telefoneCasa', $this->telefoneCasa);
    $stmt->bindParam(':emailCasa', $this->emailCasa);
    $stmt->bindParam(':enderecoCasa', $this->enderecoCasa);
    return $stmt->execute();
}

0

to execute a method of a parent class use the operator parent

$stmt = parent::prepare($sql);
  • I used it this way, but it still didn’t work. It’s strange that :/ <code> public Function Insert(){ $sql = "INSERT INTO $this->table (houseName) VALUES (:houseName)"; $stmt = Parent::prepare($sql); $stmt->bindParam(':nameCasa', $this->nameCasa); Return $stmt->execute(); } </code>

Browser other questions tagged

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