Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Anderson Narciso

Inserindo dados em duas tabelas no mesmo loop (formuláro).

Recommended Posts

Olá pessoa! Gostaria de saber se é possível inserir conteúdo em duas tabelas diferentes no mesmo loop?

 

Ex:

 

<?php if(isset($_POST['executar'])){

$ticketData = date('Y-m-d H:m:D');
$ticketPergunta = strip_tags(trim($_POST['ticket']));

$sqlTicket  = 'INSERT INTO tabela_tickets (ticketData)';
$sqlTicket .= 'VALUES (:ticketData)';

$sqlTicket  = 'INSERT INTO tabela_ticketRes (ticketPergunta)';
$sqlTicket .= 'VALUES (:ticketPergunta)';

try {
$queryTicket = $conecta->prepare($sqlTicket);
$queryTicket->bindValue(':ticketData',$ticketData,PDO::PARAM_STR);
$queryTicket->bindValue(':ticketPergunta',$ticketPergunta,PDO::PARAM_STR);
$queryTicket->execute();

echo  '<div class="ok">Cadastrado, favor aguardar a resposta antes de cadastrar outro ticket!</div>';
}catch(PDOexception $error_ticket){
  echo 'Erro ao cadastrar o seu ticket!';
}
}
?>


<form name="ticket" action="" enctype="multipart/form-data" method="post">
     <textarea rows="5" cols="125" name="ticket"></textarea>
     <input type="image" src="images/open_ticket.png" class="open_ticket" name="executar" id="executar" value="Abrir Ticket" /> 
   </form>

Finalidade: Cadastrar ID e Data em uma tabela, e perguntas e respostas na outra.

 


$sqlTicket  = 'INSERT INTO tabela_tickets (ticketData)';
$sqlTicket .= 'VALUES (:ticketData)';

$sqlTicket  = 'INSERT INTO tabela_ticketRes (ticketPergunta)';
$sqlTicket .= 'VALUES (:ticketPergunta)';

Entendem amigos?

Compartilhar este post


Link para o post
Compartilhar em outros sites

Anderson,

 

Você pode:

 

1. Criar um trigger que, ao inserir em uma tabela, separa os dados e insere na outra também. Esse é o método mais rápido para se trabalhar com essa situação.

 

2. Criar dois objetos PDOStatement e executar os dois:

 

<?php
$stm1 = $pdo->prepare( 'INSERT INTO `tabela1`(`valor`) VALUES(:valor);' );
$stm2 = $pdo->prepare( 'INSERT INTO `tabela2`(`outro`) VALUES(:outro);' );

for ( $i = 0 ; $i < 10 ; ++$i ){
$stm1->bindParam( ':valor' , $i , PDO::PARAM_INT );
$stm2->bindParam( ':outro' , $i , PDO::PARAM_INT );

$stm1->execute();
$stm2->execute();
}

 

Como estamos em PHP, o exemplo acima ilustra a solução, mas considere trabalhar com triggers.

 

;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

Dae João! É exatamente isso que eu quero, mas o problema é que não sei como usar o trigger, por isso dei o meu exemplo a cima de dois INSERT, ai to aqui batendo cabeça ): hehe

Compartilhar este post


Link para o post
Compartilhar em outros sites

mas o problema é que não sei como usar o trigger

 

Bom, exemplo rápido:

mysql> CREATE TABLE `Tabela1` (
	-> 	`idTabela1` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	-> 	`informacao` VARCHAR(45) NOT NULL
	-> );
Query OK, 0 rows affected (0.13 sec)

mysql> CREATE TABLE `Tabela2` (
	-> 	`idTabela2` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
	-> 	`idTabela1` INT NOT NULL,
	-> 	`dataRegistro` DATE NOT NULL
	-> );
Query OK, 0 rows affected (0.12 sec)

mysql> DELIMITER $$
mysql> CREATE TRIGGER `InsertDuplo` AFTER INSERT ON `Tabela1`
	-> 	FOR EACH ROW BEGIN
	-> 	INSERT INTO `Tabela2`(`idTabela1`,`dataRegistro`) VALUES(NEW.`idTabela1`,DATE(NOW()));
	-> 	END;
	-> $$
Query OK, 0 rows affected (0.27 sec)

mysql> DELIMITER ;

Bom, as tabelas estão vazias:

mysql> SELECT * FROM `Tabela1`;
Empty set (0.00 sec)

mysql> SELECT * FROM `Tabela2`;
Empty set (0.00 sec)

Inserindo alguns dados na Tabela1:

mysql> INSERT INTO `Tabela1`(`informacao`) VALUES('teste1'),('teste2'),('teste3'),('teste4');
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0

Resultado:

mysql> SELECT * FROM `Tabela1`;
+-----------+------------+
| idTabela1 | informacao |
+-----------+------------+
| 	1 | teste1 	|
| 	2 | teste2 	|
| 	3 | teste3 	|
| 	4 | teste4 	|
+-----------+------------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM `Tabela2`;
+-----------+-----------+--------------+
| idTabela2 | idTabela1 | dataRegistro |
+-----------+-----------+--------------+
| 	1 | 	1 | 2010-11-26 |
| 	2 | 	2 | 2010-11-26 |
| 	3 | 	3 | 2010-11-26 |
| 	4 | 	4 | 2010-11-26 |
+-----------+-----------+--------------+
4 rows in set (0.00 sec)

;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

Joao, to uma meia hora tentando cria esse TRIGGER, mas o bendito não cria só da erro.. Nem copiando do teu funciona )': ooo tristesa não saber nada huahua

 

Erro

 

consulta SQL:

CREATE TRIGGER 'InsertDuplo' AFTER INSERT ON 'websul_tickets'
FOR EACH
ROW BEGIN
INSERT INTO 'websul_ticketsRes'( 'ticketId', 'dataCriado', 'ticketPergunta' )
VALUES (
NEW. 'ticketId', 'DATE(NOW())', 'ticketPergunta'
);
Mensagens do MySQL : Documentação

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''InsertDuplo' AFTER INSERT ON 'websul_tickets'

FOR EACH ROW BEGIN

' at line 1

Compartilhar este post


Link para o post
Compartilhar em outros sites

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''InsertDuplo' AFTER INSERT ON 'websul_tickets'

 

Não são apóstrofos, Anderson.

 

É `InsertDuplo` não 'InsertDuplo'

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tentei criar a mesma TRIGGER, porem da um erro asssim

 

CREATE TRIGGER `InsertDuplo` AFTER INSERT ON `Tabela1`
FOR EACH
ROW BEGIN
INSERT INTO `Tabela2` ( `idTabela1` , `dataRegistro` )
VALUES (
NEW.`idTabela1` , DATE( NOW( ) )
);

Mensagens do MySQL : Documentação
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Tentei criar a mesma TRIGGER, porem da um erro asssim

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3

 

Alencar, você não deve ter percebido, mas é necessário modificar o delimitador padrão do MySQL.

 

Segue a instrução completa, inclusive com a modificação do delimitador:

DELIMITER $$

CREATE TRIGGER `InsertDuplo` AFTER INSERT ON `Tabela1`
FOR EACH ROW BEGIN
	INSERT INTO `Tabela2`(`idTabela1`,`dataRegistro`) VALUES(NEW.`idTabela1`,DATE(NOW()));
END;
$$

DELIMITER ;

 

http://forum.imasters.com.br/public/style_emoticons/default/seta.gif CREATE TRIGGER

 

Estou movendo para MySQL porque já deixou de ser PHP.

 

;)

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.