Usamos cookies para medir audiência e melhorar sua experiência. Você pode aceitar ou recusar a qualquer momento. Veja sobre o iMasters.
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>'; 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?
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
>
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;
-> $$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)
;)
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
>
#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'
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
>
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.
;)
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:
Como estamos em PHP, o exemplo acima ilustra a solução, mas considere trabalhar com triggers.
;)