Insert with Pdo and OO

Asked

Viewed 1,120 times

2

I have the following class that manages bank :

<?php
abstract class database{
    /*Método construtor do banco de dados*/
    private function __construct(){}

    /*Evita que a classe seja clonada*/
    private function __clone(){}

    /*Método que destroi a conexão com banco de dados e remove da memória todas as variáveis setadas*/
    public function __destruct() {
        $this->disconnect();
        foreach ($this as $key => $value) {
            unset($this->$key);
        }
    }

    private static $dbtype   = "mysql";
    private static $host     = "localhost";
    private static $port     = "3306";
    private static $user     = "root";
    private static $password = "";
    private static $db       = "PDO";

    /*Metodos que trazem o conteudo da variavel desejada
    @return   $xxx = conteudo da variavel solicitada*/
    private function getDBType()  {return self::$dbtype;}
    private function getHost()    {return self::$host;}
    private function getPort()    {return self::$port;}
    private function getUser()    {return self::$user;}
    private function getPassword(){return self::$password;}
    private function getDB()      {return self::$db;}

    private function connect(){
        try
        {
            $this->conexao = new PDO($this->getDBType().":host=".$this->getHost().";port=".$this->getPort().";dbname=".$this->getDB(), $this->getUser(), $this->getPassword());
        }
        catch (PDOException $i)
        {
            //se houver exceção, exibe
            die("Erro: <code>" . $i->getMessage() . "</code>");
        }

        return ($this->conexao);
    }

    private function disconnect(){
        $this->conexao = null;
    }

    /*Método select que retorna um VO ou um array de objetos*/
    public function selectDB($sql,$params=null,$class=null){
        $query=$this->connect()->prepare($sql);
        $query->execute($params);

        if(isset($class)){
            $rs = $query->fetchAll(PDO::FETCH_CLASS,$class) or die(print_r($query->errorInfo(), true));
        }else{
            $rs = $query->fetchAll(PDO::FETCH_OBJ) or die(print_r($query->errorInfo(), true));
        }
        self::__destruct();
        return $rs;
    }

    /*Método insert que insere valores no banco de dados e retorna o último id inserido*/
    public function insertDB($sql,$params=null){
        $conexao=$this->connect();
        $query=$conexao->prepare($sql);
        $query->execute($params);
        $rs = $conexao->lastInsertId() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }

    /*Método update que altera valores do banco de dados e retorna o número de linhas afetadas*/
    public function updateDB($sql,$params=null){
        $query=$this->connect()->prepare($sql);
        $query->execute($params);
        $rs = $query->rowCount() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }

    /*Método delete que excluí valores do banco de dados retorna o número de linhas afetadas*/
    public function deleteDB($sql,$params=null){
        $query=$this->connect()->prepare($sql);
        $query->execute($params);
        $rs = $query->rowCount() or die(print_r($query->errorInfo(), true));
        self::__destruct();
        return $rs;
    }
}
?>

How can I use the Insert method. For example What you would pass in the param and sql part ?

1 answer

3


You can do so by creating a class where it will inherit the database class, as in the following example where I created the Free class:

<?php

class LivroDAO extends database {

  public function __construct(){}

  public function insertLivro($data)
  {

    $sql = "INSERT INTO `tablivro` (`id`, `titulo`, `autor`, `editora`, `anoedicao`, `localizacao`) VALUES (?, ?, ?, ?, ?, ?)";
    parent::insertDB($sql, $data);

  }

  public function deleteLivro($data)
  {

    //...

  }

  public function updateLivro($data)
  {

    //...

  }

  public function selectLivro($data)
  {

        $sql = "SELECT * FROM `tablivro` WHERE `id` = ? AND `titulo` = ? AND `anoedicao` = ?";
        $result = parent::selectDB($sql, $data);

        return $result;

  }

}

To take the test you can do as follows:

<?php

require_once 'database.php';
require_once 'LivroDAO.php';

$livroDAO = new LivroDAO();

$dadosLivro = array(
  '10',
  'Livro PHP',
  'João',
  'Novatec',
  '2015',
  'São Paulo',
);

$livroDAO->insertLivro($dadosLivro);

Remembering that you have to edit the connection setting with your database in the database class, located in the following code snippet of the class:

...
private static $dbtype   = "mysql";
private static $host     = "localhost";//Seu host do banco de dados
private static $port     = "3306";
private static $user     = "root";
private static $password = "";//Sua senha
private static $db       = "PDO";//Nome do seu banco de dados
...
  • but could not do without the extend ?

  • Unless you edit the database class, you wouldn’t because the database class is Abstract, and classes of this genus can’t be instantiated.

  • this logic works for update, select and delete?

  • Yes, give same form, only implemented these methods in the Book class.

  • Friend, went wrong , returned Array ( [0] => 42S22 [1] => 1054 [2] => Unknown column 'createData' in 'field list' )

  • friend worked, it was a mistake in typing the name of a field . Thank you

  • Actually there was no error in the php code but in the syntax of the sql of Insert, where it is saying that the field createData is unknown.

  • 1

    Yes, now I decided to change the name... Obg

Show 3 more comments

Browser other questions tagged

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