How to insert data into related tables using PDO

Asked

Viewed 29 times

1

I researched a lot more I found nothing concrete with PDO, hear about this function last_insert_id but I have no idea how to apply.

1 answer

1


See an example of how to enter a neighborhood:

public function insert (Bairro $bairro){
     $this->connection =  null;
     $teste = 0;
     $this->connection = new ConnectionFactory();
     $this->connection->beginTransaction();
     try{
         $query = "INSERT INTO bairro 
                   (CD_BAIRRO, NM_BAIRRO, CD_CIDADE) 
                   VALUES 
                   (NULL, :bairro, :cidade)";
         $stmt = $this->connection->prepare($query);
         $stmt->bindValue(":bairro", $bairro->getNmBairro(), PDO::PARAM_STR);
         $stmt->bindValue(":cidade",$bairro->getCidade()->getCdCidade(), PDO::PARAM_INT);
         $stmt->execute();
         $teste =  $this->connection->lastInsertId();
         $this->connection->commit();
         $this->connection =  null;
     }catch(PDOException $exception){
         echo "Erro: ".$exception->getMessage();
     }
     return $teste;
}

I hope it helps to have a sense

Browser other questions tagged

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