Store data in the database using PDO :: commit

1

Hello ...

I've never used PDO :: Commit, but now I see the need to use ... and right now, even following the php doc and some examples on the net, I can not store the data ... here's my code :

connection.php

class Conexao extends PDO {

    private $dsn = 'mysql:host=localhost;dbname=BD';
    private $user = 'root';
    private $pass = '123456';
    private $cnn;

    public function __construct() {
        try {

            if ($this->cnn == NULL){

                $cnn = parent::__construct($this->dsn, $this->user, $this->pass);
                $this->handle = $cnn;

                return $this->handle;
            }

        } catch (PDOException $exc) {

            throw new Exception ("Mensagem: ". $exc->getMessage(). "Código de erro: ". $exc->getCode());
            return FALSE;
        }
    }

}

Clients.php

public function gravarCliente(){
        $pdo = $this->conexao = new Conexao();
        $pdo->beginTransaction();

        try{
            $sql = "INSERT INTO clientes (ID, nome, endereco, provincia, cp, telefone) VALUES (:ID, :nome, :endereco, :provincia, :cp, :telefone)";
            $exe = $this->conexao->prepare($sql);
            $exe->bindValue(':ID', $this->getID());
            $exe->bindValue(':nome', $this->getNome());
            $exe->bindValue(':endereco', $this->getEndereco());
            $exe->bindValue(':provincia', $this->getProvincia());
            $exe->bindValue(':cp', $this->getCaixaPostal());
            $exe->bindValue(':telefone', $this->getTelefone());
            $exe->execute();  

            if ($exe->execute()){ echo "Inserido"; }else{
          die("nada");}

            $pdo->commit();
        } catch (Exception $ex) {
            echo "Não foi possível registar a sua conta. Código erro: {$ex->getMessage()}";
            $pdo->rollBack();
        }

        return $exe;

    }

Thanks for the help ...

    
asked by anonymous 23.02.2015 / 09:43

1 answer

1

Here's a basic example:

<?php
/* Inicia uma transação, desligando autocommit */
$dbh->gravarCliente();

/* Inseri vários registros */
$sql = 'INSERT INTO fruit
    (name, colour, calories)
    VALUES (?, ?, ?)';

$sth = $dbh->prepare($sql);

//utilize um foreach para executar AO INVÉS DO IF
foreach ($fruits as $fruit) {
    $sth->execute(array(
        $fruit->name,
        $fruit->colour,
        $fruit->calories,
    ));
}

/* Commit confirmado */
$dbh->commit();

/* Conexão com o banco agora está no modo de autocommit */
?>

source

    
23.02.2015 / 10:38