Store data in the database using PDO::commit

Asked

Viewed 124 times

1

Hello...

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

php connection.

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;
        }
    }

}

Php clients.

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;

    }

I appreciate the help...

  • The field ID is auto increment?

1 answer

1


This is 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

Browser other questions tagged

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