Question :
Well I have 3 tables in my database, and I make a INSERT
in the sale table, and as soon as I enter the data in it automatically I would have to insert into the and the vendaproduct table that would be this code:
if(isset($_POST['send'])){
$venda = $_POST['num_venda'];
$data = $_POST['data_venda'];
$placa = $_POST['placa'];
$km = $_POST['km'];
$produtos = $_POST['produtos'];
$servicos = $_POST['servicos'];
include ('banco.php');
mysql_query("INSERT INTO venda(id_venda, num_venda, data_venda, placa, km, produtos, servicos)
values(
NULL,
'{$venda}',
'{$data}',
'{$placa}',
'{$km}',
'{$produtos}',
'{$servicos}'
)
");
mysql_query("INSERT INTO vendaproduto (id, id_venda, produtos)
SELECT venda.id_venda, venda.id_venda, venda.produtos
FROM venda");
mysql_query("INSERT INTO vendaservico (id, id_venda, servicos)
SELECT venda.id_venda, venda.id_venda, venda.servicos
FROM venda") ;
header("location:lista.php");}
The first time I tested the code it worked, but now every time I try not to insert the vendaproduct and saleservic tables, just insert the data into the table sale.
The error is as follows: Duplicate entry '1' for key 'PRIMARY'
Can I still use mysql_
to interfere with something in my code?
Answer :
Use the mysql_insert_id function to get the last record entered in sales. Then you can do insert with select but this time add a where, which compares the id with the last record inserted
if(mysql_query("INSERT INTO venda ... ")){
$id = mysql_last_id();
mysql_query("INSERT INTO vendaproduto (id, id_venda, produtos)
SELECT venda.id_venda, venda.id_venda, venda.produtos
FROM venda WHERE id = $id") or die(mysql_error());
mysql_query("INSERT INTO vendaservico (id, id_venda, servicos)
SELECT venda.id_venda, venda.id_venda, venda.servicos
FROM venda WHERE id = $id") or die(mysql_error());
}
Apparently the error you are giving is that you are trying to insert duplicate values into a single value field.
But to insert multiple values with an insert just do this:
INSERT INTO 'usuarios' ('id', 'nome', 'email') VALUES (123, 'Fulano da Silva', 'fulano@email.com'), (32, 'Ciclano', 'ciclano@uol.com.br')
You are inserting duplicate ID’s in the vendaproduto
and vendaservico
table.
If the “id” column is auto-incremental you can omit the ID column.
It would look like this:
mysql_query("INSERT INTO vendaproduto (id_venda, produtos)
SELECT venda.id_venda, venda.produtos
FROM venda");
mysql_query("INSERT INTO vendaservico (id_venda, servicos)
SELECT venda.id_venda, venda.servicos
FROM venda") ;